How to package common base test classes in plugin jar

We have an internal core plugin which is used by application and our other plugins. We have some base test classes that all our other integration test classes extends. Eg a BaseControllerIntegrationSpecification which makes it possible to write integration tests for controllers.

The common test classes has to be included in plugin jar, in order to be able to use the base test classes by other plugins and application. However when a grails plugin is packaged it does not package any of the test classes in jar. I solved this by creating a custom sourceset and copying its ourput to main sourceset before the jar is packaged.

Here is an example of how it is done.

Here is how it is done.

Create a custom sourceset

Create a custom sourceset with name testCommon with its source directory set to src/test-common/groovy. Add test dependencies and main sourceset output to the classpath of the custom sourceset.

sourceSets {
    testCommon {
        groovy {
            srcDir "src/test-common/groovy"
            compileClasspath += sourceSets.test.compileClasspath
            compileClasspath += sourceSets.main.output
        }
    }
}

Create new task to copy the classes from testCommon sourceset to main sourceset output. This will result in the test common classes being included in jar.

task copyBaseTestClasses(type: Copy) {
    from sourceSets.testCommon.output
    into sourceSets.main.output.classesDir
}

Add our copy task as dependency of the jar task so it runs before the jar is built.

jar {
    dependsOn "copyBaseTestClasses"
}

and finally add all classes from testCommon sourceset to dependency of integration tests.

dependencies {
   .......
   integrationTestCompile sourceSets.testCommon.output
}

Now all the classes from src/test-common/groovy directory will be included in jar.

Note clean, but works. Write a comment if you have some better suggestions other then creating a new plugin just for the tests and including the plugin as a testCompile dependency.

Note: You can not put your common test classes under src/main. Because spock, grails testing plugin and related dependencies are not available in main sourceset classpath, and you dont want to put those dependencies in main classpath either.