Sharing test code in a multi-module android project

Unfortunately, I have discovered a bug in this approach that prevents AS from being able to recognise classes included from another module using the sourceSets block. As an alternative, I would suggest making a specific shared test module with all of the required source code in the main source set, and adding that as a dependency to the requiring modules. If you have any alternative solutions please let me know :)

Photo by Maximilian Weisbecker on Unsplash

If you are developing a multi module android project you might find yourself requiring test files from another module (e.g. fake test classes, builders). It took me a while to find a working solution so hopefully this saves you some time.

The first thing I tried was adding the module as a dependency to the android test source set like follows:. The problem with this is gradle only provides the source files in the main source set to the implementing modules, so everything in the test and androidTest source sets is ignored.

As a workaround to the previous issue I then considered moving all of the shared test source files to the main source set of a separate test module and providing that as an dependency. Problem solved, right…? Unfortunately, some dependencies are only meant to be applied to a given source set and when applied to any other will result in build failures. An example of this is the hilt android testing library which is intended only for the android test source set (), adding it as a dependency to the main source set ( ) will result in test failures.

Sourcesets

As well as adding another module as a dependency to include source code, like the previous approaches, gradle also allows you to include source sets of other modules via the block:

sourceSets {
androidTest {
java.srcDir project(":module-a").file("src/androidTest/java")
}
}

Breaking this block down in reverse we:

  1. Add the source files under
  2. In the
  3. To the source directories ()
  4. In the
  5. For the implementing module

No more copy pasting the same builder classes in multiple modules.

Please let me know if you have any alternative solutions that work too :)

anything and everything android