我使用了一个叫做spring-cloud-aws的依赖模块。在我的SpringBoot JUnit测试用例中,它有一个@Configuration类作为org.springframework.cloud.aws.messaging.config.annotation.SqsConfiguration,检测到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测试用例注入凭据。
org.springframework.beans.factory.BeanCreationException:创建类路径资源org/springframework/cloud/aws/messaging/config/annotation/SqsConfiguration.class:中定义的名为'simpleMessageListenerContainer‘的bean时出错;init方法调用失败;嵌套异常为com.amazonaws.services.sqs.model.AmazonSQSException:请求中包含的安全令牌已过期
发布于 2019-09-08 03:58:52
有多种方法可以在测试过程中排除特定的自动配置:
通过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)选择一个更适合你的;)
发布于 2021-03-09 22:01:22
因此,要禁用Test的所有Beans的自动加载,测试类可以显式地提到所需的依赖项。这可以使用ContextConfiguration注释来完成。例如,
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {EmployeeService.class})
public class EmployeeLeavesTest {
@Autowired
private EmployeeService employeeService;
}在这个例子中,只有EmployeeService类是可用的,其他bean将不会被加载。
https://stackoverflow.com/questions/57828851
复制相似问题