【问题标题】:How to load a @Profile service in spring-test?如何在 spring-test 中加载@Profile 服务?
【发布时间】: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


【解决方案1】:

它通过在静态内部 @TestConfiguration 类中初始化 Bean 来工作。

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

虽然MvcInterceptor 取决于@Profile,但它会为测试连接。

【讨论】:

    猜你喜欢
    • 2019-04-17
    • 1970-01-01
    • 2021-01-23
    • 2016-12-07
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多