【问题标题】:How to exclude classes with @Configuration in @SpringBootApplication testing如何在@SpringBootApplication 测试中使用@Configuration 排除类
【发布时间】:2020-01-09 17:39:08
【问题描述】:

我正在使用一个名为 spring-cloud-aws 的依赖模块。它有一个 @Configuration 类作为 org.springframework.cloud.aws.messaging.config.annotation.SqsConfiguration 在我的 SpringBoot JUnit 测试用例中,检测到 SqsConfiguration 类并初始化 Bean。我想在我的 JUNit 测试用例中排除这个配置。如何做到这一点?

我尝试使用@ComponentScan,但它不起作用。

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SQLTestConfig.class)
@ActiveProfiles("test")
public class BusinessManagerTest {

}

@TestConfiguration
@ComponentScan(basePackages = {"package1","package1"},
excludeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = SqsConfiguration.class)})
@Profile("test")
class SQLTestConfig {   

    @Bean
    public SomeBean beans() {

        return new SomeBean();
    }



}

加载此配置类需要可用的 aws 凭据。我不想注入凭据来运行一个简单的 Bean 测试用例。

org.springframework.beans.factory.BeanCreationException:在类路径资源 [org/springframework/cloud/aws/messaging/config/annotation/SqsConfiguration.class] 中定义名称为“simpleMessageListenerContainer”的 bean 创建错误:调用 init 方法失败的;嵌套异常是 com.amazonaws.services.sqs.model.AmazonSQSException: 请求中包含的安全令牌已过期

【问题讨论】:

    标签: spring-boot spring-cloud-aws


    【解决方案1】:

    在测试期间有多种方法可以排除特定的自动配置:

    • 通过application-test.properties 中的属性排除
    spring.autoconfigure.exclude=org.springframework.cloud.aws.messaging.config.annotation.SqsConfiguration
    
    • 通过@TestPropertySource排除:
    @RunWith(SpringRunner.class)
    @ActiveProfiles("test")
    @SpringBootTest(classes = SQLTestConfig.class)
    @TestPropertySource(properties ="spring.autoconfigure.exclude=org.springframework.cloud.aws.messaging.config.annotation.SqsConfiguration")
    
    
    • 通过@EnableAutoConfiguration 排除,例如:
    @RunWith(SpringRunner.class)
    @ActiveProfiles("test")
    @SpringBootTest(classes = SQLTestConfig.class)
    @EnableAutoConfiguration(exclude=SqsConfiguration.class)
    
    

    选择一个更适合你的;)

    【讨论】:

      【解决方案2】:

      因此,要禁用自动加载测试的所有 Bean,测试类可以明确提及所需的依赖项。这可以使用ContextConfiguration 注释来完成。例如,

      @ExtendWith(SpringExtension.class)
      @ContextConfiguration(classes = {EmployeeService.class})
      public class EmployeeLeavesTest { 
      
         @Autowired
         private EmployeeService employeeService;
      
      }
      

      在这个例子中,只有 EmployeeService 类可用,其他 bean 不会被加载。

      【讨论】:

        猜你喜欢
        • 2020-06-21
        • 1970-01-01
        • 2021-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-27
        • 2014-12-29
        • 1970-01-01
        相关资源
        最近更新 更多