I have a Spring Boot integration test and a Spring Boot web integration test. Both tests pass when run individually. However, when run as part of a suite, the test that is executed second always fails. Each test starts up (and tears down) my application and, in turn, my h2
database. I have experimented with swapping the order of the tests and it always the latter test that fails.
What can I do to ensure that these tests are self-contained/will not affect each other?
Note: I am using the class annotations @RunWith(SpringRunner.class)
and @SpringBootTest
for both tests, with the web integration test passing the argument webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT
to the latter annotation.
Integration test:
@Test
public void testFindAll() {
List<Object> objects = objectRepository.findAll();
assertThat(objects.size(), is(greaterThanOrEqualTo(0)));
}
Web integration test:
@Test
public void testListAll() throws IOException {
TestRestTemplate testRestTemplate = new TestRestTemplate();
ResponseEntity<String> responseEntity = testRestTemplate.getForEntity("url/api/v1/objects", String.class);
assertThat(responseEntity.getStatusCode(), equalTo(OK));
ObjectMapper objectMapper = new ObjectMapper();
JsonNode responseJson = objectMapper.readTree(responseEntity.getBody());
assertThat(responseJson.isMissingNode(), is(false));
assertThat(responseJson.toString(), equalTo("[]"));
}
I had a similar problem, though my tests involve changes on an embedded H2 DB. I solved it by annotating my classes with @DirtiesContext
This will have Spring reload ApplicationContext after your test.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With