【问题标题】:Spring boot test configuration not being picked未选择 Spring Boot 测试配置
【发布时间】:2017-01-25 21:16:56
【问题描述】:

我正在为我的应用程序编写集成测试,并希望为我的测试使用自定义 webmvc 配置

我的基础包 com.marco.nutri 中有三个类:

  • 应用程序(使用@SpringBootApplication注解)
  • MvcConfig(@Configuration 和@EnableWebMVC)
  • SecurityConfig(@Configuration 和 @EnableWebSecurity)

我的测试在包 br.com.marco.nutri.integration.auth 中:

@RunWith(SpringRunner.class)
@SpringBootTest(classes={Application.class, WebMvcTestConfiguration.class, SecurityConfig.class})
public class ITSignup {

    //Test code

}

我在 com.marco.nutri.integration 包中有一个测试配置类:

@TestConfiguration
@EnableWebMvc
public class WebMvcTestConfiguration extends WebMvcConfigurerAdapter {
    //Some configuration
}

但是当我运行测试时,选择的是 MvcConfig.class 而不是 WebMvcTestConfiguration.class

我做错了什么?

【问题讨论】:

    标签: java spring spring-boot spring-test


    【解决方案1】:

    你可以用@Profile("test")注释你的测试配置,用@Profile("production")注释你的真实配置

    在你的属性文件中放入属性spring.profiles.active=production,在你的测试类中放入@Profile("test")。因此,当您的应用程序启动时,它将使用“生产”类,而当测试启动时,它将使用“测试”类。

    来自文档

    与常规的@Configuration 类不同,@TestConfiguration 的使用 不会阻止@SpringBootConfiguration 的自动检测。

    与嵌套的 @Configuration 类不同,后者将被用来代替 你的应用程序的主要配置,一个嵌套的@TestConfiguration 除了您的应用程序的主要类之外,还将使用类 配置。

    【讨论】:

    • 但是当我从生产类中删除配置时,它会选择带有 TestConfiguration 的类
    • 你怎么知道根本没有选择带有 TestConfiguration 的类..你是使用断点还是打印一些东西?
    • 我只是问,因为运行两个配置类会有点棘手,因为 @TestConfiguration 不会替换生产类。他们俩将一起工作。
    • 如果您希望这两个类相互替换,您可以在我的回答中使用建议的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 2018-11-02
    • 2019-01-20
    • 2018-12-03
    • 1970-01-01
    相关资源
    最近更新 更多