简体   繁体   中英

Spring: override beans in integration tests with isolation

I have a problem with overriding beans in integration tests in Spring (with Spock).

Let's say this is my application config:

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

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

And I have 2 separate integration tests that I want to have to separate Car implementations provided.

@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();
        }
    }
}

When I run one of these I am getting: NoUniqueBeanDefinitionException cause Spring detects there are multiple car implementations. How to make test inner class Config with @Configuration annotation being loaded only for that particular test? I saw the approach with @Profile but that would mean creating separate profiles names for each IntegrationSpec which is a little bit violating a DRY. Is there another approach than @ActiveProfiles ?

I'm finding it hard to understand your use-case. Do you have to initialize entire applicationContext to test FerrariCar and TeslaCar? Can't you test them in isolation?

If integration test is the only way to go, you could try excludeFilters in @ComponentScan to disable auto-detecting your test config, as illustrated in https://stackoverflow.com/a/30199808/1553203 . You can then add specific test @Configuration for each Spec/Test by using @Import/@ComponentScan.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM