在 @SpringWebMvc 测试中排除从 Spring Boot 应用程序导入的配置

问题描述 投票:0回答:1

我正在使用一个多模块 Spring Boot 应用程序,该应用程序从其他模块导入配置。

@SpringBootApplication
@Import({
  FooConfiguration.class,
  BarConfiguration.class
})    
public class SpringBootApplication { ... }

并想为

@WebMvcTest
写一个
@RestController
。加载应用程序上下文时,应禁用在
SpringBootApplication
类中导入的配置。

我已经尝试使用

@WebMvcTest#excludeAutoConfiguration
来排除
SpringBootApplication.cass
本身以及
@WebMvcTest#excludeFilters
来排除包含配置类的包。他们都不适合我。

spring-boot integration-testing spring-test spring-boot-test
1个回答
0
投票

因为

FooConfiguration
BarConfiguration
只是普通配置类,不是自动配置类,而
excludeAutoConfiguration
只对自动配置类生效。

另外

excludeFilters
@ComponentScan
的属性,因此只有在组件扫描时检测到配置类时才会生效,但如果使用
@Import
显式定义则不起作用。

修复此问题的一种简单方法是使用

@Profile
有条件地导入这些外部模块配置,这样在运行测试时就不会导入它们。

喜欢的东西:

@SpringBootApplication
@Import(ExternalModuleConfiguration.class)
public class SpringBootApplication { ... }


@Configuration
@Import({FooConfiguration.class, BarConfiguration.class}) 
@Profile("!test")  
public class ExternalModuleConfiguration {
}

然后在测试中,将活动配置文件设置为

test
,这样
ExternalModuleConfiguration
将不会被导入:

@ActiveProfiles("test")
@WebMvcTest
public class BootTest {

}
© www.soinside.com 2019 - 2024. All rights reserved.