java - 测试Spring Boot应用程序启动

标签 java spring spring-boot junit spring-test

我有一个 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 选项非常重要。它可以采用诸如 NONEMOCKRANDOM_PORTDEFINED_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/

相关文章:

java - Android Firebase 数据库路径无效

java - 静态方法的行为与其他可以重写的方法类似

java - 复杂的 Activiti + JPA 查询

java - 将内部 json 对象转换为字符串

java - Windows 服务器中的 Spring Boot 应用程序

java - JPanel 背景图像不适用于其中的 JPanel

java - spring和hibernate同步访问数据库的方法

spring - 如何在 Spring Data 的查询中使用表函数

java - 访问rest-api方法getAll时获取数据失败

java - 在 YML 中的接口(interface)列表中设置类