首页 > 解决方案 > 是否可以在 WebMvcTest 中激活弹簧配置文件

问题描述

给定一个测试类,如:

@WebMvcTest
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "spring.profiles.active=test")
public class MyControllerTest  {
... some tests
}

我得到错误:

java.lang.IllegalStateException:配置错误:发现测试类 [com.example.MyControllerTest] 的多个 @BootstrapWith 声明:[@org.springframework.test.context.BootstrapWith(value=class org.springframework.boot.test.autoconfigure .web.servlet.WebMvcTestContextBootstrapper), @org.springframework.test.context.BootstrapWith(value=class org.springframework.boot.test.context.SpringBootTestContextBootstrapper)]

期望的目标是我只是在运行控制器测试,因此出于测试性能的原因不想设置整个上下文 - 我只想要“Web层”。

我可以删除该@SpringBootTest(properties = "spring.profiles.active=test")行 - 但是,现在我还没有激活测试配置文件,它可以通过属性以某种方式自定义 Web 上下文,例如不再应用的杰克逊自定义。有没有办法让“网络层”只测试并仍然激活弹簧配置文件?

我的环境是java version "10.0.2" 2018-07-17,spring boot1.5.16.RELEASE

标签: spring-bootspring-testspring-boot-testspring-webspring-test-mvc

解决方案


要设置活动配置文件,您可以使用@ActiveProfiles,像这样

@WebMvcTest
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
public class MyControllerTest  {

然后你可以application-test在测试资源中使用 yml 或属性。


推荐阅读