Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot integration tests failing when run after one another

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("[]"));
}
like image 655
Blair Nangle Avatar asked Jun 12 '17 18:06

Blair Nangle


1 Answers

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.

like image 74
Marcel Avatar answered Nov 03 '22 23:11

Marcel