简体   繁体   English

如何防止SpringJUnit4ClassRunner加载所有@Configuration类

[英]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). 但是在加载WebAppConfigTest类之后,它将加载具有@Configuration并且不在测试包(src / test / java)中的WebAppConfig类。

Note: the class WebAppConfig is not configured to be loaded into the unit test, but still is being charged. 注意:WebAppConfig类未配置为加载到单元测试中,但仍在收费。

WebAppConfig Class WebAppConfig类

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

WebAppConfigTest Class WebAppConfigTest类

@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. 对于组件扫描,Spring不会将包与src / test / java或src / main / java区别开。

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

is essentially scanning all the @Configurations,all packages within current package and sub-packages starting from "br.com.example". 本质上是从“ br.com.example”开始扫描所有@Configurations,当前软件包和子软件包中的所有软件包。 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. 您可以使用@ComponenScan中的过滤器来包含/排除特定的程序包/类。 You can avoid the unwanted classes to be picked up by spring when loading the application context this way. 这样加载应用程序上下文时,可以避免spring不需要的类。
  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. 如果可以手动选择所需的配置以加载测试的上下文,则甚至可以完全删除@ComponentScan并在“ classes”属性中指定所有配置类。
  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. 您可以在配置类中使用@Profile,在测试类中使用@ActiveProfiles来映射要在特定配置文件中加载的配置类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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