Issue
I am writing some integration tests in which I need to send in an api call to create a resource and then perform subsequent api calls based on that resource. I wanted to send the first call inside my @BeforeAll method.
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class ExampleResourceTest {
@Autowired
private MockMvc mockMvc;
@BeforeAll
private void createExampleResource() throws Exception {
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("email", "[email protected]");
requestBody.put("username", "example");
requestBody.put("firstName", "Example");
requestBody.put("lastName", "Name");
requestBody.put("password", "@password123");
Gson gson = new Gson();
String json = gson.toJson(requestBody);
mockMvc.perform(
post("/api/v1/resourcename")
.contentType(MediaType.APPLICATION_JSON)
.content(json));
}
// More stuff...
}
However, the method annotated @BeforeAll method is not being called before I run the tests in the class.
As I understand from trying to find a solution, @BeforeAll methods need to be static. However, then I wouldn't be able to use my injected MockMvc. I've also tried annotating my test class with
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
, but I've faced no luck with that either.
Solution
It turns out I was on junit 4 and needed to use @BeforeClass to be able to call it. I ended up instead using an @Before method and just using a boolean value to check if the call had already been made.
Answered By - Mansehaj Singh
Answer Checked By - Mary Flores (JavaFixing Volunteer)