简体   繁体   中英

How to prevent the SpringJUnit4ClassRunner load all @Configuration classes

In my unit test class, I have the following configuration:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = WebAppConfigTest.class)
public class ExampleTest {

But after loading the WebAppConfigTest class, it's loading my WebAppConfig class that has @Configuration and is out of the test package (src/test/java).

Note: the class WebAppConfig is not configured to be loaded into the unit test, but still is being charged.

WebAppConfig Class

@EnableWebMvc
@ComponentScan(basePackages = {"br.com.example"})
@PropertySource(value="classpath:application.properties")
@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {

WebAppConfigTest Class

@ComponentScan(basePackages = {"br.com.example"})
@Configuration
public class WebAppConfigTest {

How to prevent this class out of the test package is loaded?

Spring doesn't differentiate packages from src/test/java or src/main/java for your component scan.

@ComponentScan(basePackages = {"br.com.example"})

is essentially scanning all the @Configurations,all packages within current package and sub-packages starting from "br.com.example". These are the options available for you:

  1. Change your package structure to give a more specific package to scan for test classes.
  2. You can use the filters in @ComponenScan to include/exclude specific packages/classes. You can avoid the unwanted classes to be picked up by spring when loading the application context this way.
  3. If its possible to handpick the required configurations to load the context for tests, you can even remove the @ComponentScan altogether and specify all the configuration classes in "classes" attribute.
  4. You can use @Profile in your configuration classes and @ActiveProfiles in your test classes to map the configuration classes to be loaded in specific profiles.

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