加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 测试启动Spring-boot应用程序

发布时间:2020-12-15 04:49:02 所属栏目:Java 来源:网络整理
导读:我有一个JUnit测试,在测试后启动一个 spring-boot应用程序(在我的例子中,主类是 SpringTestDemoApp): @WebIntegrationTest@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(classes = SpringTestDemoApp.class)public class Spring
我有一个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,或尝试自动装配端口号并尝试在该端口上运行测试.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读