测试启动Spring-boot应用程序

Bon*_*cía 4 java junit spring spring-test spring-boot

我有一个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)
    }
}
Run Code Online (Sandbox Code Playgroud)

使用弹簧靴一切正常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
    }

}
Run Code Online (Sandbox Code Playgroud)

如何重构我的测试以使其在spring-boot 1.5中工作?

小智 9

webEnvironment选项里面@SpringBootTest是非常重要的.它可以采取类似的值NONE,MOCK,RANDOM_PORT,DEFINED_PORT.

  • NONE 将只创建spring bean而不是任何模拟servlet环境.

  • MOCK 将创建spring bean和模拟servlet环境.

  • RANDOM_PORT将在随机端口上启动实际的servlet容器; 这可以使用自动装配@LocalServerPort.

  • DEFINED_PORT 将获取属性中定义的端口并使用它启动服务器.

默认是RANDOM_PORT您没有定义任何内容webEnvironment.所以应用程序可能会在不同的端口为您启动.

尝试覆盖它DEFINED_PORT,或尝试自动装配端口号并尝试在该端口上运行测试.

  • 默认值为MOCK,至少使用Spring Boot 1.5.10. (2认同)