是否可以在 WebMvcTest 中激活 spring 配置文件
Is it possible to activate a spring profile in a WebMvcTest
给了一个测试 class 比如:
@WebMvcTest
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "spring.profiles.active=test")
public class MyControllerTest {
... some tests
}
我收到错误:
java.lang.IllegalStateException: Configuration error: found multiple declarations of @BootstrapWith for test class [com.example.MyControllerTest]: [@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 layer".
我可以删除 @SpringBootTest(properties = "spring.profiles.active=test")
行 - 但是,现在我还没有激活测试配置文件,它可以通过属性以某种方式自定义 Web 上下文,例如将不再应用的杰克逊定制。有没有办法获得仅 "web layer" 测试并仍然激活 spring 配置文件?
我的环境是javaversion "10.0.2" 2018-07-17
,spring开机1.5.16.RELEASE
要设置活动配置文件,您可以使用 @ActiveProfiles
,像这样
@WebMvcTest
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
public class MyControllerTest {
那么你可以 application-test
yml 或测试资源中的属性。
此外,如果您以如下编程方式获取活动配置文件:
String environment = System.getProperty("spring.profiles.active");
然后你可以在测试的静态块中设置这个 属性 class:
@WebMvcTest
public class MyControllerTest {
static {
System.setProperty("spring.profiles.active", "foo");
}
}
给了一个测试 class 比如:
@WebMvcTest
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "spring.profiles.active=test")
public class MyControllerTest {
... some tests
}
我收到错误:
java.lang.IllegalStateException: Configuration error: found multiple declarations of @BootstrapWith for test class [com.example.MyControllerTest]: [@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 layer".
我可以删除 @SpringBootTest(properties = "spring.profiles.active=test")
行 - 但是,现在我还没有激活测试配置文件,它可以通过属性以某种方式自定义 Web 上下文,例如将不再应用的杰克逊定制。有没有办法获得仅 "web layer" 测试并仍然激活 spring 配置文件?
我的环境是javaversion "10.0.2" 2018-07-17
,spring开机1.5.16.RELEASE
要设置活动配置文件,您可以使用 @ActiveProfiles
,像这样
@WebMvcTest
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
public class MyControllerTest {
那么你可以 application-test
yml 或测试资源中的属性。
此外,如果您以如下编程方式获取活动配置文件:
String environment = System.getProperty("spring.profiles.active");
然后你可以在测试的静态块中设置这个 属性 class:
@WebMvcTest
public class MyControllerTest {
static {
System.setProperty("spring.profiles.active", "foo");
}
}