gpt4 book ai didi

java - Spring ComponentScan excludeFilters 注释在 Spring Boot 测试上下文中不起作用

转载 作者:搜寻专家 更新时间:2023-11-01 02:59:00 24 4
gpt4 key购买 nike

我正在使用 Spring Boot 1.4.3.RELEASE 并希望在运行测试时排除某些组件被扫描。

@RunWith(SpringRunner.class)
@SpringBootTest
@ComponentScan(
basePackages = {"com.foobar"},
excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {AmazonKinesisRecordChecker.class, MyAmazonCredentials.class}))
public class ApplicationTests {

@Test
public void contextLoads() {
}

}

尽管有过滤器,当我运行测试时,不需要的组件被加载并且 Spring Boot 崩溃,因为这些类需要 AWS 环境才能正常工作:

2017-01-25 16:02:49.234 ERROR 10514 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'amazonKinesisRecordChecker' defined in file

问题:如何让过滤器正常工作?

最佳答案

您需要的不是排除它们,而是使用 @MockBean 模拟它们。如下图

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
@MockBean
AmazonCredentials amazonCredentials;

@Test
public void contextLoads() {
}
}

通过这种方式,您将让 Spring Context 知道您想要模拟 AmazonCredentials bean。有时,排除过滤器使用起来有点棘手。

希望对您有所帮助!我很乐意探索我们是否有其他方法来完成这项工作。

关于java - Spring ComponentScan excludeFilters 注释在 Spring Boot 测试上下文中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41843861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com