2016-08-16 59 views
0

我在Spring中(使用Spock)集成测试中的重写Bean有一个问题。Spring:在集成测试中用隔离覆盖bean

比方说,这是我的应用程序配置:

@EnableWebMvc 
@SpringBootApplication 
@Configuration 
class Main { 
    @Bean 
    Race race(Car car) { 
     // ... 
    } 

    @Bean 
    Car car() { 
     // ... 
    } 
} 

而且我有我想有分开提供Car实现2次独立的集成测试。

@Slf4j 
@SpringApplicationConfiguration 
class OneIntegrationSpec extends AbstractIntegrationSpec { 

    @Configuration 
    @Import(Main.class) 
    static class Config { 
     @Bean 
     Car oneTestCar() { 
      return new FerrariCar(); 
     } 
    } 
} 


@Slf4j 
@SpringApplicationConfiguration 
class OtherIntegrationSpec extends AbstractIntegrationSpec { 

    @Configuration 
    @Import(Main.class) 
    static class Config { 
     @Bean 
     Car otherTestCar() { 
      return new TeslaCar(); 
     } 
    } 
} 

当我运行的这些我得到一个:NoUniqueBeanDefinitionException原因春天检测有多个汽车实现。 如何使内部类Config@Configuration注释仅为特定测试加载? 我看到@Profile的方法,但这意味着要为每个IntegrationSpec创建单独的配置文件名称,这有点违反了DRY。除@ActiveProfiles之外是否还有另一种方法?

+0

一个快速和肮脏的解决方案可能是简单地声明您的测试bean @Primary,这将绕过一个事实,即有多个合适的bean,因为那时将使用主要候选bean。 –

+0

是的,但是当我在'* IntegrationSpec'中得到'@ Primary'时出现同样的问题 – dmydlarz

+0

为什么要同时加载两个'IntegrationSpec'?您没有显示测试本身(以及如何加载Spring上下文),但可能不会对这些类使用组件扫描。 –

回答

0

我发现很难理解你的用例。你是否必须初始化整个applicationContext来测试FerrariCar和TeslaCar?你不能单独测试它们吗?

如果集成测试是唯一的出路,您可以尝试使用@ComponentScan中的excludeFilters来禁用自动检测您的测试配置,如https://stackoverflow.com/a/30199808/1553203中所示。然后,您可以使用@ Import/@ ComponentScan为每个Spec/Test添加特定的测试@Configuration。