I have struggled with a similar issue for one day... My Scenario:
I have a SpringBoot application and I use applicationContext.xml in scr/main/resources
to configure all my Spring Beans.
For testing(integration testing) I use another applicationContext.xml in test/resources
and things worked as I have expected: Spring/SpringBoot would override applicationContext.xml from scr/main/resources
and would use the one for Testing which contained the beans configured for testing.
However, just for one UnitTest I wanted yet another customization for the applicationContext.xml used in Testing, just for this Test I wanted to used some mockito beans, so I could mock
and verify
, and here started my one day head-ache!
The problem is that Spring/SpringBoot doesn't not override the applicationContext.xml from scr/main/resources
ONLY IF the file from test/resources
HAS the SAME NAME.
I tried for hours to use something like:
@RunWith(SpringJUnit4ClassRunner.class)
@OverrideAutoConfiguration(enabled=true)
@ContextConfiguration({"classpath:applicationContext-test.xml"})
it did not work, Spring was first loading the beans from applicationContext.xml in scr/main/resources
My solution based on the answers here by @myroch and @Stuart:
Define the main configuration of the application:
@Configuration
@ImportResource({"classpath:applicationContext.xml"})
public class MainAppConfig {
}
this is used in the application
@SpringBootApplication
@Import(MainAppConfig.class)
public class SuppressionMain implements CommandLineRunner
Define a TestConfiguration for the Test where you want to exclude the main configuration
@ComponentScan(
basePackages = "com.mypackage",
excludeFilters = {
@ComponentScan.Filter(type = ASSIGNABLE_TYPE,
value = {MainAppConfig.class})
})
@EnableAutoConfiguration
public class TestConfig {
}
By doing this, for this Test, Spring will not load applicationContext.xml and will load only the custom configuration specific for this Test.
CRaSSHD
supposed to be? – Unlettered@SpringApplicationConfiguration
prevents@EnableAutoConfiguration
from taking effect), it's worth noting that in test-slice composite annotations like@DataJpaTest
, we see that they use combinations of@OverrideAutoConfiguration(enabled=false)
to broadly disable auto configuration and@ImportAutoConfiguration(classes...)
to turn specific configuration back on. These continue to work as new auto-configuration elements are added to the application. – Albinus