Using test fixtures in Gradle and Maven

In Maven if you want to reuse text fixtures from one module in another module, you use the jar plugin and build a test jar. You have to specify what classes and other resources to include. Gradle has a dedicated plugin to handle this. Apply the plugin:
plugins {
  id ’java-test-fixtures'
}
Create a directory src/testFixtures/java for your classes. You can add these test fixtures to the classpath of another module as follows:
testImplementation(testFixtures(project(':some-module:some-sub-module')))
For more info, see the Gradle docs on java testing: https://docs.gradle.org/current/userguide/java_testing.html

If you still need to support the Maven build at the same time, you must make two changes, to make both resources and java classes available to your test jar build. Resources can be specified in the top level of your build config:

<build>
    <testResources>
        <testResource>
            <directory>src/test/resources</directory>
        </testResource>
        <testResource>
            <directory>src/testFixtures/resources</directory>
        </testResource>
    </testResources>
To support a new test source location, you must use the Maven build helper plugin:
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <executions>
        <execution>
            <id>add-gradle-testfixtures</id>
            <phase>generate-test-sources</phase>
            <goals>
                <goal>add-test-source</goal>
            </goals>
            <configuration>
                <sources>
                    <source>src/testFixtures/java</source>
                </sources>
            </configuration>
        </execution>
    </executions>
</plugin>
This entry was posted in Gradle, Java and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

HTML tags are not allowed.

517,978 Spambots Blocked by Simple Comments