Home > Software design >  Spring boot: reference pom properties from application.properties in tests
Spring boot: reference pom properties from application.properties in tests

Time:11-13

This is my src/test/resources/application.yml:

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

I'm just trying to get the model version from my pom file:

<?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>
...

The test:

@WebMvcTest(ProfilingController.class)
public class RestControllerTest {

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

    @Test
    public void testHelloEnv() throws Exception {

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

    }
}

The error I get:

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@
               ^

The funny part is that I got the same property in the src/main/resource/application.yml, but in that case when I run the app normally, version: @modelVersion is correctly populated from pom and I can get the version without issues. It's like test's application.yml is not aware of pom.xml

any thoughts?

NOTE: using '@modelVersion' between single quotes prevents the error but I get the string @modelVersion instead of its value 4.0.0

Tech:

  • Spring boot version: 2.5.6
  • Junit version: Jupiter (5)
  • Maven version: 3.8.3

CodePudding user response:

As described in the documentation resource filtering is enabled by the spring-boot-starter-parent

That is not the case for 'test' properties, so if you need this, you need to enable filtering in the test-resources:

in your pom.xml

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