Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share test classes across Gradle projects? [duplicate]

Tags:

java

gradle

I am using Gradle to build and test my projects. I have two projects:

ProjA  contains      src\test\java\BaseTest.java       
ProjB  contains      src\test\java\MyTest.java

MyTest extends BaseTest

When I run ProjB.gradle, how do I get it to see the BaseTest class from ProjA?

I tried adding:

dependencies {
  testCompile project('ProjA') 
}

But it didn't work.

like image 645
Britboy Avatar asked Aug 04 '15 16:08

Britboy


1 Answers

Maybe there are better, simpler ways, cleaner ways, but I think you have three options here.

First option

Since BaseTest is a class that is in fact part of a reusable testing library (you use it in both projects), you could simply create a testing subprojects, where BaseTest is defined in src/main/java and not src/test/java. The testCompile configuration of the other two subprojects would both have a dependency on project('testing').

Second option (UPDATED for Gradle 7.3)

In this second option, you would define an additional artifact and configuration in the first project:

configurations {
  testClasses {
    extendsFrom(testImplementation)
  }
}

task testJar(type: Jar) {
  archiveClassifier.set('test')
  from sourceSets.test.output
}

// add the jar generated by the testJar task to the testClasses dependency
artifacts {
  testClasses testJar
}

and you would depend on this configuration in the second project:

dependencies {
  testCompile project(path: ':ProjA', configuration: 'testClasses')
}

Third option

Basically the same as the second one, except it doesn't add a new configuration to the first project:

task testJar(type: Jar) {
  archiveClassifier.set('test')
  from sourceSets.test.output
}

artifacts {
  testRuntime testJar
}

and

dependencies {
  testCompile project(path: ':one', configuration: 'testRuntime')
}
like image 190
JB Nizet Avatar answered Sep 28 '22 00:09

JB Nizet