我有一个 JUnit 测试,它在测试后启动一个 spring-boot 应用程序(在我的例子中,主类是 SpringTestDemoApp
):
@WebIntegrationTest
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringTestDemoApp.class)
public class SpringTest {
@Test
public void test() {
// Test http://localhost:8080/ (with Selenium)
}
}
使用 spring-boot 1.3.3.RELEASE
一切正常。尽管如此,注释@WebIntegrationTest
和@SpringApplicationConfiguration
已在spring-boot 1.5.2.RELEASE
中删除。我尝试将代码重构到新版本,但我无法做到。通过以下测试,我的应用程序在测试之前未启动,并且 http://localhost:8080返回 404:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringTestDemoApp.class)
@WebAppConfiguration
public class SpringTest {
@Test
public void test() {
// The same test than before
}
}
如何重构我的测试以使其在 spring-boot 1.5 中工作?
最佳答案
@SpringBootTest
中的 webEnvironment
选项非常重要。它可以采用诸如 NONE
、MOCK
、RANDOM_PORT
、DEFINED_PORT
之类的值。
NONE
只会创建 spring bean,不会模拟 servlet 环境。MOCK
将创建 spring bean 和模拟 servlet 环境。RANDOM_PORT
将在随机端口上启动实际的 servlet 容器;这可以使用@LocalServerPort
自动连接。DEFINED_PORT
将采用属性中定义的端口并用它启动服务器。
当您未定义任何webEnvironment
时,默认值为RANDOM_PORT
。因此,该应用程序可能会在不同的端口上为您启动。
尝试将其覆盖为DEFINED_PORT
,或尝试自动连接端口号并尝试在该端口上运行测试。
关于java - 测试Spring Boot应用程序启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43281370/