【问题标题】:Is it possible to activate a spring profile in a WebMvcTest是否可以在 WebMvcTest 中激活弹簧配置文件
【发布时间】:2019-03-21 12:54:53
【问题描述】:

给定一个测试类,例如:

@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 上下文,例如将不再应用的杰克逊自定义。有没有办法让“web 层”仅测试并仍然激活弹簧配置文件?

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

【问题讨论】:

  • 如果您之前不知道,here 可能是几个选项
  • 这是一篇很好的文章,展示了各种测试方法,但我没有看到任何与此相关的内容。
  • activate a spring profile 是什么意思。您要激活哪个弹簧配置文件?
  • 自定义的。在这种情况下,它称为test。即类路径上有一个application-test.properties 文件。该文件可以执行诸如设置杰克逊序列化选项之类的操作,这些选项可以更改应用程序的行为。激活配置文件后,结果可能与未激活时不同,因此我想在测试中激活它。

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


【解决方案1】:

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

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

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

【讨论】:

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

此外,如果您以这样的程序化方式获得活跃的个人资料:

String environment = System.getProperty("spring.profiles.active");

然后你可以在你的测试类的静态块中设置这个属性:

@WebMvcTest
public class MyControllerTest  {
    static {
        System.setProperty("spring.profiles.active", "foo");
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-21
    • 2016-12-25
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    • 2014-10-14
    • 1970-01-01
    • 2017-04-12
    相关资源
    最近更新 更多