spring-boot - 如何在@SpringBootApplication测试中使用@Configuration排除类

标签 spring-boot spring-cloud-aws

我正在使用一个名为 spring-cloud-aws 的依赖模块。它有一个 @Configuration 类作为 org.springframework.cloud.aws.messaging.config.annotation.SqsConfiguration 在我的 SpringBoot JUnit 测试用例中,SqsConfiguration 类被检测到并且 Beans 被初始化。我想在我的 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 测试用例注入(inject)凭据。

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

最佳答案

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

  • 通过 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)

选择一个更适合你的;)

关于spring-boot - 如何在@SpringBootApplication测试中使用@Configuration排除类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57828851/

相关文章:

java - 将 SpringCloud Finchley 升级到 RELEASE 时缺少 AmazonS3Client Bean

spring-mvc - 带有 XML 模板的 Spring Boot 和 Thymeleaf

spring - 在 Grails 3 中将 JNDI 添加到嵌入式 Tomcat 服务器

spring-boot - 版本 spring boot、spring cloud、ribbon 不工作

spring-boot - Spring Batch ChunkRequest 抛出 stackOverflow

amazon-web-services - 使用@SqsListener时,Spring Boot应用程序启动时失败

java - Spring Boot Rest api 更新列

spring-cloud-aws - 从 Hoxton.SR4 升级到 Spring Cloud Hoxton.SR7 后遇到错误

spring-integration - 我如何在 spring-integration-aws 中使用 sqs-message-driven-channel-adapter