【问题标题】:Spring ComponentScan excludeFilters annotation not working in Spring Boot Test contextSpring ComponentScan excludeFilters 注释在 Spring Boot Test 上下文中不起作用
【发布时间】:2017-06-10 04:14:59
【问题描述】:

我正在使用 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 

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

【问题讨论】:

标签: java spring spring-boot spring-annotations spring-test


【解决方案1】:

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

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

    @Test
    public void contextLoads() {
    }
}

这样你会让 Spring Context 知道你想模拟 AmazonCredentials bean。有时,排除过滤器有点棘手。

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

【讨论】:

    猜你喜欢
    • 2018-06-14
    • 2014-10-22
    • 2016-06-02
    • 2014-07-05
    • 2016-11-23
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 2019-12-18
    相关资源
    最近更新 更多