【问题标题】:Exclude few @Component annotated classes in SpringBootTest在 SpringBootTest 中排除少数 @Component 注解的类
【发布时间】:2020-02-21 05:28:56
【问题描述】:

我有几个 @Component 注释类,我在其中初始化了我的配置器,例如 DBConfigurer、SecurityConfigurer、JmxConfigurer 等等。

在添加功能测试时,我希望不应该加载几个类。我可以排除上面定义的几个配置器吗?

我的测试类我定义如下:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { ServiceStarter.class }, properties = { "jmx.rmi.port=19057", "hostname=localhost" })
@ContextConfiguration(classes = {ControllerTest.BeansOverrideConfigurer.class})
public class ControllerTest {
    // All test here.
}

我可以在测试类的 @ContextConfiguration 块中定义选定的配置器,但我不想这样做,因为将来如果有人添加新的配置器,它应该会自动导入到测试用例中。

【问题讨论】:

    标签: java junit annotations spring-boot-test


    【解决方案1】:

    在您不想在特定配置文件期间加载的那些组件上使用@Profile,例如测试(即仅在生产和开发期间)。

    @Component
    @Profile("production")
    public class ComponentClass {}
    

    然后定义您想要在测试期间运行的@ActiveProfile,例如

    @SpringBootTest
    @ActiveProfiles("test")
    public class ControllerTest {}
    

    您可以参考 Spring Framework 文档和 Spring Boot 文档了解更多信息docs.spring.io

    【讨论】:

      猜你喜欢
      • 2019-09-15
      • 1970-01-01
      • 2018-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-30
      • 1970-01-01
      相关资源
      最近更新 更多