How to share tests between multiple projects?

Another option is to copy the tests from project T into projects A & B under a “$buildDir/generated” folder prior to test compile. You could then run the tests in your IDE via the “generated” versions of each test case

Eg:

[':A', ':B'].each {
   project(it) {
      apply plugin: 'java'
      task generateTestSources(type: Copy) {
         ext.outputDir = "$buildDir/generated/test/java"
         from project(':T').file('src/main/java')
         into outputDir
      }
      compileTestJava.dependsOn generateTestSources
      sourceSets.test.java.srcDir generateTestSources.outputDir
   }
}

Bonus points for

  • Repackaging the tests into A and B packages as part of the copy (this will help junit reporting)
  • Setting the Eclipse’s “derived” flag on the $buildDir/generated/test/java" folders
  • Calling File.setReadOnly() on the generated files so you don’t accidentally attempt to edit them (and subsequently have your changes overridden next copy)