spring-boot - 如何在@SpringBootApplication 测试中使用@Configuration 排除类
问题描述
我正在使用一个名为 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:请求中包含的安全令牌已过期
解决方案
有多种方法可以在测试期间排除特定的自动配置:
- 通过您的属性排除
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)
选择一个更适合你的;)
推荐阅读
- python - 传递函数将忽略的参数
- javascript - 如何在 node.js 函数中应用 Promise
- postgresql - 错误:运算符不存在:数字 = 字符变化
- spring - MVC 中的 Spring Cache - 可以使用自动装配进行查找吗?
- .net - Docker 容器启动(“docker run”)但立即停止(ASP .NET MVC api-REST 解决方案)
- java - 使用 Java 在 XML 中设置嵌入字段的文本
- sql - 连接具有相同键的表,第二个表有多个键值,第二个表的行必须具有相同的列值
- jenkins - Docker 上的詹金斯。-- Hello World 示例构建失败
- node.js - Node js在生产服务器上部署和运行时无法将文件上传到FTP
- javascript - 像我们在excel中输入的公式验证