我的项目中有一堆测试,它们都是用@SpringBootTest注释的,因此加载了一个SpringBoot上下文。
最近我重构了一个测试,其中我想要一个更小的范围(它是关于camunda的进程复盖)到@RunWith(SpringJUnit4ClassRunner.class)。由于这意味着不会自动加载任何上下文,因此我使用静态内部类配置“手动”创建了一些bean。整个测试看起来像这样:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {
ExternalConfiguration.class, MyTest.InternalConfiguration.class
})
public class MyTest{
@Autowired
private SomeBean someInternalBean;
@Configuration
public static class InternalConfiguration{
@Bean
SomeBean someInternalBean() {
return mock(SomeBean .class);
}
}
//Tests现在,当我运行该测试时,它运行得很好。但是当我运行任何其他测试(那些仍然用@SpringBootTest注解的测试)时,我在加载ApplicationContext时遇到问题:
The bean 'someInternalBean', defined in class path resource [.../MyTest$InternalConfiguration.class], could not be registered. A bean with that name has already been defined in file [.../SomeBean.class] and overriding is disabled.显然,在加载组件时会创建一个bean,因为该类使用@ ApplicationContext进行了注释,并且上下文加载器尝试从我的内部配置创建另一个bean。
我不能允许bean覆盖,因为我的模拟bean可能会覆盖自动创建的bean(它们确实会覆盖,我已经尝试过了)。
我该如何规避这个问题呢?我希望我的SpringJUnit4ClassRunner-test及其内部配置不会影响其他@SpringBootTest-test。我已经尝试使用@ConditionalOnMissingBean使配置bean具有条件,但这不起作用。
发布于 2019-08-29 16:50:28
原来这些内部配置类不应该用@Configuration注解。删除注释可以使手动bean生成仍然有效,并且配置不再由componentScan拾取。
https://stackoverflow.com/questions/57705827
复制相似问题