如何在spring-test中加载@Profile服务?

时间:2018-03-01 14:33:23

标签: java spring spring-boot spring-test spring-test-mvc

如何在@Profile中加载spring-test组件,而无需将该配置文件明确启动为启动配置文件?

@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(...))...;
    }
}

问题:如何在测试类中不使用MvcInterceptor加载@ActiveProfiles("dev1")

因为,dev1个人资料意味着会设置更多资源,而我不需要进行该测试。我只想加载MvcInterceptor,但无需启动完整的个人资料。

不可能?

1 个答案:

答案 0 :(得分:0)

它的工作原理是在静态内部Bean类中初始化@TestConfiguration

public class SpringTest {
    @TestConfiguration
    public static class TestConfig {
        @Bean
        public MvcInterceptor interceptor() {
            return new MvcInterceptor();
        }
    }
}

虽然MvcInterceptor取决于@Profile,但它会连线进行测试。