Spring ComponentScan excludeFilters 注释在 Spring 引导测试上下文中不起作用

Spring ComponentScan excludeFilters annotation not working in Spring Boot Test context

我正在使用 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 引导崩溃,因为那些 类 需要 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 上下文知道你想要模拟 AmazonCredentials bean。有时,排除过滤器有点棘手。

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