【问题标题】:Why test in spring boot application still works without @RunWith(SpringRunner.class) just with @SpringBootTest为什么在没有 @RunWith(SpringRunner.class) 的情况下仅使用 @SpringBootTest 在 Spring Boot 应用程序中进行测试
【发布时间】:2021-04-14 08:56:26
【问题描述】:

我不明白为什么我的执行测试在没有@RunWith(SpringRunner.class) 的情况下工作得很好。我在测试类上方只有@SpringBootTest。请解释下一个案例: 1)什么时候我必须同时设置@RunWith(SpringRunner.class)和@SpringBootTest? 2)当我只能设置 @RunWith(SpringRunner.class) 和 @SpringBootTest 使用是多余的? 3)当我只能设置 @SpringBootTest 和 @RunWith(SpringRunner.class) 使用是多余的?

我的代码执行良好的测试是:

@SpringBootTest
//@RunWith(SpringRunner.class)
class SpringBootSimpleTestExampleApplicationTests {


    @Autowired
    private ApplicationContext applicationContext;


    @Test
    void contextLoads() {
        Object restTempalte = applicationContext.getBeanDefinitionCount();
        Assertions.assertThat(applicationContext).isNotNull();
    }

}

【问题讨论】:

  • 你使用的是junit 4还是junit 5?
  • 我使用 Junit 4 并且我的 pom 配置是下一个:spring-boot-starter-test 带有排除的复古引擎和明确定义的没有版本的 junit 依赖
  • 您能否将您的pom.xmlimport 部分添加到您的问题中?

标签: junit spring-boot-test


【解决方案1】:

@SpringBootTest

在 spring-test 中 @ContextConfiguration(classes=…​) 注解提供的常规 Spring TestContext 之外,它提供了以下功能。

不使用嵌套@Configuration 类时自动搜索@SpringBootConfiguration,并且没有指定显式类。 允许使用 properties 属性定义自定义环境属性。 提供对不同 webEnvironment 模式的支持,包括启动在定义或随机端口上侦听的完全运行的 Web 服务器的能力。 注册一个 TestRestTemplate 和/或 WebTestClient bean,以便在使用完全运行的 Web 服务器的 Web 测试中使用。

https://howtodoinjava.com/spring-boot2/testing/springboottest-annotation/

【讨论】:

    猜你喜欢
    • 2018-05-15
    • 2016-12-14
    • 1970-01-01
    • 2020-04-03
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 2016-06-01
    • 2018-04-01
    相关资源
    最近更新 更多