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.
In my test class:
@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.
CodePudding user response:
I believe the @BeforeAll
should not be private but you have added that.
That is the reason it is not invoking your method.
Refer: https://junit.org/junit5/docs/5.0.0/api/org/junit/jupiter/api/BeforeAll.html
CodePudding user response:
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.