In a multi-module project, you may end up in a situation where you need same functionality for tests in multiple modules. For instance, if you have a ‘common’ module with some testing utilities that you’d like to use in other modules as well. Let’s wire our Gradle files to allow us to do that!

Gradle Configuration

Let’s say you have two modules: a common module which contains common logic used by multiple modules, and an app module which is your Android application that makes use of the common module. You’d like to use some of the classes in the common module’s tests in app’s tests.

This is a rather simple thing to do. First off, in your common module, define this task:

task jarTest(type: Jar) {
    from sourceSets.test.output
    classifier = 'test'
}

This little task creates a new JAR with all the classes from your tests. This is the JAR we will later on use in the other module to access the classes.

Now, let’s define a new configuration for our common module called testOutput:

configurations {
    testOutput
}

Whenever we want to create the JAR for our tests, this is the configuration we will use. Finally, let’s define what artifacts we want to output in this configuration:

artifacts {
    testOutput jarTest
}

There we go, our common module is now fully configured. Now, to pull the JAR as a dependency to the app module, let’s define it in the app module’s dependencies:

dependencies {
    testCompile project(path: ':common', configuration: 'testOutput')
}

And we are done! Now you can write tests in your app module and use any and all classes you have defined in your common module’s tests. As always, if you found this post useful, consider buying me a cup of coffee - it’ll power me to write more stuff!