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

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

如何在@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,但无需启动完整的配置文件。

不可能?

java spring spring-boot spring-test spring-test-mvc
1个回答
0
投票

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

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

虽然MvcInterceptor取决于@Profile,但它将用于测试。

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