spring-boot - 是否可以在 WebMvcTest 中激活 Spring 配置文件

标签 spring-boot spring-test spring-boot-test spring-web spring-test-mvc

给定一个测试类,如:

@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)]



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

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

我的环境是java version "10.0.2" 2018-07-17 , Spring Boot 1.5.16.RELEASE

最佳答案

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

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

那么你可以application-test yml 或测试资源中的属性。

关于spring-boot - 是否可以在 WebMvcTest 中激活 Spring 配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52844801/

相关文章:

spring-boot - 使用Mybatis+Springboot开发的应用程序通过junit测试无法调用Mapper.xml文件

java - Spring 安全,启动 : replace default DaoAuthenticationProvider

spring - java.lang.IllegalStateException(未找到方法) : Calling MockMvc. 使用自定义 Filter 在一次测试中执行多次

spring-security - 在 Spring MVC 单元测试中模拟匿名认证

java - Spring Boot 测试 - @WithMockUser 发布的内容为空

spring-boot - @JdbcTest 检测带有@SpringBootApplication 注释的类

java - Spring Boot 默认 H2 jdbc 连接(和 H2 控制台)

spring-boot - 使用spring嵌入式ldap模拟事件目录进行集成测试

java - 为什么以及何时使用动态 servlet 注册?

jpa - 没有可用的事务 EntityManager