簡體   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