Spring 引导集成测试在 运行 接一个失败时失败
Spring Boot integration tests failing when run after one another
我有一个 Spring 启动集成测试和一个 Spring 启动 Web 集成测试。当单独 运行 时,两个测试都通过了。但是,当 运行 作为套件的一部分时,第二个执行的测试总是失败。每个测试都会启动(并关闭)我的应用程序,进而启动我的 h2
数据库。我已经尝试过交换测试的顺序,但总是后一个测试失败。
我该怎么做才能确保这些测试self-contained/will不会相互影响?
注意: 我在两个测试中都使用了 class 注释 @RunWith(SpringRunner.class)
和 @SpringBootTest
,Web 集成测试通过了参数webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT
到后面的注释。
集成测试:
@Test
public void testFindAll() {
List<Object> objects = objectRepository.findAll();
assertThat(objects.size(), is(greaterThanOrEqualTo(0)));
}
网络集成测试:
@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("[]"));
}
我遇到了类似的问题,尽管我的测试涉及对嵌入式 H2 数据库的更改。我通过用 @DirtiesContext
注释我的 类 解决了这个问题这将 Spring 在测试后重新加载 ApplicationContext。
我有一个 Spring 启动集成测试和一个 Spring 启动 Web 集成测试。当单独 运行 时,两个测试都通过了。但是,当 运行 作为套件的一部分时,第二个执行的测试总是失败。每个测试都会启动(并关闭)我的应用程序,进而启动我的 h2
数据库。我已经尝试过交换测试的顺序,但总是后一个测试失败。
我该怎么做才能确保这些测试self-contained/will不会相互影响?
注意: 我在两个测试中都使用了 class 注释 @RunWith(SpringRunner.class)
和 @SpringBootTest
,Web 集成测试通过了参数webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT
到后面的注释。
集成测试:
@Test
public void testFindAll() {
List<Object> objects = objectRepository.findAll();
assertThat(objects.size(), is(greaterThanOrEqualTo(0)));
}
网络集成测试:
@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("[]"));
}
我遇到了类似的问题,尽管我的测试涉及对嵌入式 H2 数据库的更改。我通过用 @DirtiesContext
注释我的 类 解决了这个问题这将 Spring 在测试后重新加载 ApplicationContext。