0

我不知道如何在测试中排除配置(例如,如此处 所述)。我真正想要的是忽略@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 { }
}

为什么ExcludedBeantestExclusion()? 如何正确排除配置?

4

1 回答 1

1

上面的测试类将通过 @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.
}
于 2020-01-27T00:35:59.603 回答