是否可以在WebMvcTest中激活弹簧配置文件

Dav*_*vid 1 spring-test spring-test-mvc spring-boot spring-web spring-boot-test

给定一个类似的测试类:

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

我得到错误:

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上下文,例如将不再应用的杰克逊自定义。有没有一种方法可以只对“ Web层”进行测试并仍然激活弹簧轮廓?

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

Ami*_*kar 5

要设置有效的个人资料,您可以@ActiveProfiles像这样使用

@WebMvcTest
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
public class MyControllerTest  {
Run Code Online (Sandbox Code Playgroud)

那么您可以application-testyml或测试资源中的属性。

  • 如果您有一些基于配置文件的组件,则不会创建该组件。例如,我在 DEV 和测试配置文件中创建了一个组件,当我使用 @WebMvcTest 和 @ActiveProfiles("test") 运行 ControllerTest 时,applicationContext 不会创建该组件。 (2认同)