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 :)
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:
androidTestImplementation project(":module-withTestFiles"). 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
androidTestImplementation project(":module-withTestFilesInMain") 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 (
androidTestImplementation 'com.google.dagger:hilt-android-testing:2.33-beta'), adding it as a dependency to the main source set (
implementation 'com.google.dagger:hilt-android-testing:2.33-beta') will result in test failures.
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
Breaking this block down in reverse we:
- Add the source files under
- In the
- To the source directories (
- In the
- 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 :)