[英]How to load a @Profile service in spring-test?
How can I load a @Profile
component in a spring-test
, without having to explicit launch that profile as startup profile? 如何在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(...))...;
}
}
Question: how can I load the MvcInterceptor
without using @ActiveProfiles("dev1")
on the testclass? 问题:如何在MvcInterceptor
不使用@ActiveProfiles("dev1")
来加载MvcInterceptor
?
Because, dev1
profile would imply many more resources being set up, which I won't need for that test. 因为, dev1
配置文件将暗示要设置更多的资源,而我不需要进行该测试。 I just want to load the MvcInterceptor
, but without having to launch the full profile. 我只想加载MvcInterceptor
,而不必启动完整的配置文件。
Impossible? 不可能?
It works by initializing the a Bean
in a static inner @TestConfiguration
class. 它通过在静态内部@TestConfiguration
类中初始化Bean
来工作。
public class SpringTest {
@TestConfiguration
public static class TestConfig {
@Bean
public MvcInterceptor interceptor() {
return new MvcInterceptor();
}
}
}
Though MvcInterceptor
is @Profile
depending, it will be wired for the test. 尽管MvcInterceptor
是@Profile
依赖的,但它将为测试连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.