Maven - Add directory to classpath while executing tests

The Junits I have in my project need to load property files from the classpath. How can I specify the directory of those property files so that Maven will set that in the classpath before running the tests?


Solution 1:

You can also add new test resource folders.

<build>
    <testResources>
        <testResource>
            <directory>${project.basedir}/src/test/resources</directory>
        </testResource>
        <testResource>
            <directory>${project.basedir}/src/test/something_else</directory>
        </testResource>
    </testResources>
</build>

The first path, src/test/resources, is the default. Assuming you still want the default path to be used, make sure it's included. (The testResources tag overwrites your defaults, so if you don't include the default path explicitly, it will stop being used.)

Solution 2:

You can use the build-helper-maven-plugin to specify additional test-resource directories as follows. Using the configuration below, the contents of the test-resources directory will be copied to the target/test-classes directory during the generate-test-sources phase:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>build-helper-maven-plugin</artifactId>
  <version>1.12</version>
  <executions>
    <execution>
      <id>add-test-resource</id>
      <phase>generate-test-sources</phase>
      <goals>
        <goal>add-test-resource</goal>
      </goals>
      <configuration>
        <resources>
          <resource>
            <directory>path/to/additional/test/resources</directory>
            <excludes>
              <exclude>**/folder-to-exclude/**</exclude>
            </excludes>
          </resource>
        </resources>
      </configuration>
    </execution> 
  </executions>
</plugin>

Solution 3:

If you just want to put your property files someplace on disk and don't want to copy those property files to target/test-classes during the build, you can do it this way

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <configuration>
    <additionalClasspathElements>
      <additionalClasspathElement>/add/this/to/path</additionalClasspathElement>
    </additionalClasspathElements>
  </configuration>
</plugin>

Solution 4:

Why not just use test/resources and place your properties in the classpath from that point. They'll only be there for the test phase.

Solution 5:

If you have multiple resource environment you can use maven profile and put your various resources according to the profile you are testing.

test/resources/uat
test/resources/prod
test/resources/dev

But usualy if you need that you are making integration test then you don't need the build-helper-maven-plugin.