【发布时间】:2018-03-01 14:33:23
【问题描述】:
如何在spring-test 中加载@Profile 组件,而无需将该配置文件显式启动为启动配置文件?
@Configuration
@Profile("dev1")
public class MvcInterceptor extends WebMvcConfigurerAdapter {
//adding a custom interceptor
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MappedInterceptor("/customer", new CustomerInterceptor()));
super.addInterceptors(registry);
}
}
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
//@ActiveProfiles("dev1") //I don't want spring to load the full profile chain
public class SpringTest {
@Autowired
protected MockMvc mvc;
@Test
public void test() {
mvc.perform(get(...))...;
}
}
问题:如何在 testclass 上不使用@ActiveProfiles("dev1") 来加载MvcInterceptor?
因为,dev1 配置文件意味着要设置更多资源,而我在该测试中不需要这些资源。我只想加载MvcInterceptor,但不必启动完整的配置文件。
不可能?
【问题讨论】:
-
对于 MvcInterceptor 类你可以设置
@Profile("dev1", "test")。这样,也只为测试配置文件加载这个类 -
虽然这可行,但我想防止使用特定于测试的代码污染我的普通类...
-
你可以尝试用
@ContextConfiguration加载特定的类,但只要你在那个类上有@Profile,spring就不会加载它。
标签: java spring spring-boot spring-test spring-test-mvc