簡體   English   中英

Spring Boot:在測試中從 application.properties 引用 pom 屬性

[英]Spring boot: reference pom properties from application.properties in tests

這是我的 src/ test /resources/ application.yml

app:
  name: Configuration And Profiles
  desc: This is an app to try out ${app.name}
  version: @modelVersion@

我只是想從我的pom 文件中獲取模型版本:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
...

考試:

@WebMvcTest(ProfilingController.class)
public class RestControllerTest {

    @Value("${app.version}")
    private String version;

    @Test
    public void testHelloEnv() throws Exception {

        System.out.println("VERSION: " + version);

    }
}

我得到的錯誤:

org.yaml.snakeyaml.scanner.ScannerException: while scanning for the next token
found character '@' that cannot start any token. (Do not use @ for indentation)
 in 'reader', line 4, column 12:
      version: @modelVersion@
               ^

有趣的是,我在 src/ main /resource/application.yml 中得到了相同的屬性,但在這種情況下,當我正常運行應用程序時,版本:@modelVersion 是從 pom 正確填充的,我可以毫無問題地獲得版本. 就像 test 的 application.yml 不知道 pom.xml

有什么想法嗎?

注意:在單引號之間使用 '@modelVersion' 可以防止錯誤,但我得到字符串 @modelVersion 而不是它的值 4.0.0

技術:

  • Spring啟動版本:2.5.6
  • Junit版本:木星(5)
  • Maven 版本:3.8.3

文檔中所述,資源過濾由spring-boot-starter-parent啟用

'test' 屬性不是這種情況,所以如果你需要這個,你需要在測試資源中啟用過濾:

在你的 pom.xml

    <build>
        <testResources>
            <testResource>
                <directory>src/test/resources</directory>
                <filtering>true</filtering>
            </testResource>
        </testResources>
    ...
    </build>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM