ComponentScan忽略excludeFilters(测试中)

问题描述 投票:0回答:1

我不知道如何在测试中排除配置(例如described here)。我真正想要的是忽略@WebMvcTest中的配置,但是即使以下更简单的示例也不适用于我:

@ExtendWith(SpringExtension.class)
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {
        ComponentScanTest.ExcludedConfig.class }))
class ComponentScanTest {

    @Autowired
    private ApplicationContext applicationContext;

    @Test
    void testInclusion() throws Exception { // This test succeeds, no exception is thrown.
        applicationContext.getBean(IncludedBean.class); 
    }

    @Test
    void testExclusion() throws Exception { // This test fails, because ExcludedBean is found.
        assertThrows(NoSuchBeanDefinitionException.class, () -> applicationContext.getBean(ExcludedBean.class));
    }

    @Configuration
    static class IncludedConfig {
        @Bean
        public IncludedBean includedBean() {
            return new IncludedBean();
        }
    }

    static class IncludedBean { }

    @Configuration
    static class ExcludedConfig {
        @Bean
        public ExcludedBean excludedBean() {
            return new ExcludedBean();
        }
    }

    static class ExcludedBean { }
}

为什么在ExcludedBean中找到testExclusion()?如何正确排除配置?

java spring component-scan
1个回答
0
投票

上面的测试类将带有@Profile批注以控制Bean的创建。

@ExtendWith(SpringExtension.class)
@ComponentScan
@ActiveProfiles("web")
class ComponentScanTest {

    @Autowired
    private ApplicationContext applicationContext;

    @Test
    void testInclusion() throws Exception { // This test succeeds, no exception is thrown.
        applicationContext.getBean(IncludedBean.class);
    }

    @Test
    void testExclusion() throws Exception { // This test fails, because ExcludedBean is found.
        assertThrows(NoSuchBeanDefinitionException.class, () -> applicationContext.getBean(ExcludedBean.class));
    }

    @Configuration
    @Profile("web")
    static class IncludedConfig {
        @Bean
        public IncludedBean includedBean() {
            return new IncludedBean();
        }
    }

    static class IncludedBean {
    }

    @Configuration
    @Profile("!web")
    static class ExcludedConfig {
        @Bean
        public ExcludedBean excludedBean() {
            return new ExcludedBean();
        }
    }

    static class ExcludedBean {
    }
}

更新:以下代码适用于@ComponentScan

根据需要创建一个配置类并用@ComponentScan进行注释

@Configuration
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {
        ComponentScanTest.ExcludedConfig.class }))
public class TestConfiguration {

}

并如下提供测试类的ApplicationContext

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes= {TestConfiguration.class})
class ComponentScanTest {
  //.. Everything else remains the same.
}
© www.soinside.com 2019 - 2024. All rights reserved.