【问题标题】:Springboot test with different properties per location每个位置具有不同属性的 Spring Boot 测试
【发布时间】:2018-08-31 15:48:56
【问题描述】:

简而言之我的问题: 如何在不同环境中运行具有不同属性的测试?

长版: 我写了一个 JUnit-Test,在类顶部注释如下:

@RunWith(SpringRunner.class)
@SpringBootTest( classes=RunServer.class, webEnvironment = WebEnvironment.DEFINED_PORT )
@TestPropertySource(locations="file:conf/application-junit.properties")
public class MyDbTest {...

在当前的conf/application.junit.properties中有5400端口上数据库连接的语句。

但现在我发现我不仅在本地运行测试,还在数据库端口位于 5500 的另一台机器上运行测试,比如 Jenkins。

我确实有一个带有正确端口的属性文件,它位于 conf/application-jenkins.properties

现在我想知道如何在源代码中为 @TestPropertySource(locations=...) 设置正确的值?

顺便说一句。这对于我只设置为参数的非测试代码执行来说完全没有问题
java -jar myjar.jar --spring.config.location=
我的属性文件不在类路径中。它们被设置为绝对文件路径。

感谢大家的帮助。

【问题讨论】:

  • 看看在这种情况下是否可以使用spring.profiles.include。只是一种预感。没有亲自尝试过

标签: java spring spring-boot properties


【解决方案1】:

你不应该指定:

@TestPropertySource(locations="file:conf/application-junit.properties")

这会在测试类中硬编码junit Spring Boot 配置文件。

相反,您应该根据设置为mvn test的配置文件执行测试,例如:

mvn clean test -Dspring.profiles.active=junit

mvn clean test -Dspring.profiles.active=jenkins

application-junit.propertiesapplication-jenkins.properties 将根据spring.profiles.active 值集自动用于创建ApplicationContext。

【讨论】:

  • ...仅仅两年后...有人想:我可以激活多个配置文件,不是吗?那么会使用哪些属性呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-12
  • 2018-11-14
  • 2019-04-15
  • 2015-01-16
  • 2021-02-01
相关资源
最近更新 更多