繁体   English   中英

mvn test - 覆盖 application.properties 中的值

[英]mvn test - override values in application.properties

我的application.properties中有这些属性:

spring.datasource.url=jdbc:postgresql://localhsost:5432/myDatabase
spring.datasource.username=myUsername

我想使用上述以外的其他值运行mvn test ,例如:

spring.datasource.url=jdbc:postgresql://my.test.server.com:5432/myDatabase
spring.datasource.username=anotherUsername

我尝试了以下

mvn test -Drun.arguments='--spring.datasource.jdbc:postgresql://my.test.server.com:5432/myDatabase --spring.datasource.username=anotherUsername'

并且没有spring前缀:

mvn test -Drun.arguments='--datasource.jdbc:postgresql://my.test.server.com:5432/myDatabase --datasource.username=anotherUsername'

但这似乎不起作用。 如何在运行mvn test的上下文中覆盖application.properties中的值?

这样的事情应该工作:

  <plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.20.1</version>
    <configuration>
      <systemPropertyVariables>
        <spring.datasource.jdbc>value</spring.datasource.jdbc>
      </systemPropertyVariables>
    </configuration>
  </plugin>

但更多情况下,我们通过将application.properties的测试版本放入src/test/resources做到这一点。 在测试期间,该文件将具有更高的优先级。

在命令行中覆盖参数时,使用逗号作为分隔符,而不是空格:

mvn test -Drun.arguments='--spring.datasource.url=...,--spring.datasource.username=...'

这也应该有效:

mvn test -Dspring.datasource.url=... -Dspring.datasource.username=...

2021 年 4 月起编辑

上面的语法对 Spring Boot 1.X 有效。 使用 Spring Boot 2.0/2.1,使用:

mvn test -Dspring-boot.run.arguments='--spring.datasource.url=...,--spring.datasource.username=...'

在 Spring Boot 2.2 中,再次更改了语法(使用空格作为分隔符):

mvn test -Dspring-boot.run.arguments='--spring.datasource.url=... --spring.datasource.username=...'

其他答案和评论提到使用配置文件并将自定义application.properties放在/src/test/resources ,这对您来说不是一个可行的解决方案,因为您使用不同的管道,但如果我没记错的话,您甚至可以使用application-{profile}.properties/src/test/resources 通过这种方式,您应该能够为每个管道维护一个测试配置文件,您可以在其中放置自定义参数,然后使用以下命令测试您的管道:

mvn test -Dspring.profiles.active=foobar

选项 1首选,因为 Maven 结构特定

test/resources下创建一个application.properties以进行测试

选项 2Spring Test 单独微调特定的测试类

通过使用@TestPropertySource内联您想要的属性,直接在 Test 类上覆盖您的属性

选项 3Spring Boot - 多个属性文件或单个 YAML 文件

在 Spring Profile 下将 props 分组( 此处的示例)并直接从 maven 调用它: mvn test -Dspring.profiles.active="myOtherSpringProfile"

创建另一个application-dev.properties文件并粘贴:

spring.datasource.url=jdbc:postgresql://my.test.server.com:5432/myDatabase
spring.datasource.username=anotherUsername

然后在mvn命令中使用选项-Dspring.profiles.active=dev运行。

  • 例如: mvn test -Dspring.profiles.active=dev

您可以根据需要添加任意数量的配置文件。

  • 语法: application-<profile name>.properties

我没有看到很多人使用环境变量选项。 如果为相应的属性设置环境变量,则将使用环境变量中的值。 例如

环境变量:SPRING_DATASOURCE_URL="jdbc:postgresql://my.test.server.com:5432/myDatabase" SPRING_DATASOURCE_USERNAME=anotherUsername

在属性文件中:spring.datasource.url=jdbc:postgresql://localhsost:5432/myDatabase spring。

应用程序将使用环境变量中的值。 为此,您需要遵循命名约定。 使用大写并替换“.” 和 ”_”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM