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

How to load a @Profile service in spring-test?

如何在 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(...))...;
    }
}

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

因为,dev1 配置文件意味着要设置更多资源,而我在该测试中不需要这些资源。我只想加载 MvcInterceptor,但不必启动完整配置文件。

不可能?

它通过在静态内部 @TestConfiguration class.

中初始化 a Bean 来工作
public class SpringTest {
    @TestConfiguration
    public static class TestConfig {
        @Bean
        public MvcInterceptor interceptor() {
            return new MvcInterceptor();
        }
    }
}

虽然 MvcInterceptor@Profile 取决于,它会被连接以进行测试。