开发者

Is there a portable way to get the path of a resource in a Maven project?

开发者 https://www.devze.com 2023-03-24 01:04 出处:网络
One of my unit tests is driven by test data, stored in src/test/resources/te开发者_运维问答stData.txt. Since Maven will copy the contents of src/test/resources to target/test-classes/ which is on the

One of my unit tests is driven by test data, stored in src/test/resources/te开发者_运维问答stData.txt. Since Maven will copy the contents of src/test/resources to target/test-classes/ which is on the classpath, I can read that file conveniently from the classpath without caring about its absolute file name. So far, so good.

Now I'm in the process of witing some code that will update that file with data fetched from a remote system. That code will be run rarely, and not as part of the build. The updated file will be committed to the source repository. In order to append to the file, I need to know the path to the original file in src/test/resources (appending to the one in target/test-classes/ will obviously not work).

How do I determine that path in a portable way? I'd rather not hard code src/test/resources/, because those directory names may actually change. Also, this would break if executed with a current working directory other than my project base directory.

Any ideas?


The best way would probably be with ${project.basedir}/src/test/resources. The test resource directory is unlikely to change, and it will safely resolve to the correct path regardless of your working directory. Trying to reference a test resource directory via a property is problematic because there can be, and often are, multiple test resources defined. How would you know which one to pick?


My preferred solution to this is to configure the surefire plugin to expose the ${project.basedir} as an environment variable during test execution. Unit tests can then read that information from the environment if required. This keeps all configuration in the POM and will require no changes should that path ever change:

<build>
    <plugins>
        ...
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            ...
            <configuration>
                ...
                <environmentVariables>
                    <maven.project.basedir>${project.basedir}</maven.project.basedir>
                </environmentVariables>
            </configuration>
        </plugin>
        ...
    </plugins>
</build>

Other solutions could be implemented using resource filtering (as suggested by Ryan) or by configuring the surefire plugin to add ${project.basedir}/src/test/resources/ to the classpath.

0

精彩评论

暂无评论...
验证码 换一张
取 消