【问题标题】:How to override application-test.yml in spring boot test?如何在春季启动测试中覆盖 application-test.yml?
【发布时间】:2019-08-17 10:50:45
【问题描述】:

我有 src/main/test/resources/application-test.yml,根据 SpringBootTest,它将加载 application.yml,然后加载 application-test.yml。但是我面临这样一种情况,我只想为一个测试覆盖 application-test.yml 中的某些属性,而其他测试需要使用 application-test.yml 中的属性。我该怎么做?

我尝试使用@TestPropertySource 注释来覆盖,但它不起作用。

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes= MyApplicationTestApplication.class)
@ActiveProfiles("test")
@DirtiesContext
@TestPropertySource(locations = {"classpath:application-test.yml",
                                    "classpath:file-test.properties"})

【问题讨论】:

  • 对于这个Now again I want to override certain properties,你可以使用application-test.yml 对吗?
  • 我已经在使用 application-test.yml 了。问题是如何覆盖 application-test.yml 中的属性,因为我需要只为我的一项测试覆盖某些属性。
  • @TestPropertySource 覆盖其他所有内容。所以只需添加file-test.properties 并留下@ActiveProfile。 Spring 将基于该上下文和特殊设置引导一个新上下文。您可能不需要@DirtiesContext,除非您希望在每次测试之前重新启动所有内容。
  • @M.Deinum file-test.properties 在 Spring 引导时不被考虑。还使用 DirtiesContext 因为我需要它重新启动,因为每个测试的模拟 bean 都不同。
  • 你为什么需要@DirtiesContext@MockBean 实例已放置在上下文中。属性文件在类路径中吗?因为它确实应该被考虑在内。看起来你正在做你不应该做的事情,因此会破坏引导代码。

标签: java spring-boot spring-boot-test


【解决方案1】:

如何再创建一个配置文件并激活它们(订单很重要)@ActiveProfiles({"test", "test-override"})

或者您可以在 spring 上下文开始加载之前使用 System.properties 覆盖,例如在静态块中。

【讨论】:

  • 我不想创建另一个配置文件。但它虽然有效。但这行得通。
  • 虽然这行得通,但是有一个配置文件只是为了覆盖属性所以这对我有用@SpringBootTest(properties = "some.property=localhost:9094")
【解决方案2】:

感谢 cmets 和回答,只是想添加对我有用的内容

@SpringBootTest(properties = "some.property=localhost:9094") 

Link to doc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 2021-08-31
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多