Edit (August 16, 2022): This method is outdated and no longer works on the latest versions of Android Studio. See my new guide for an up-to-date solution on this problem.
Here's the dilemma: you've got some utility code that you'd like all of your tests to share but
src/test can't use code from
src/androidTest and vice versa. You could put that code into
src/main but you want to avoid shipping test code. How else do you share the code between the tests?
The solution I've come up with is to leverage source sets to define common code. First, I put my shared test code into
src/sharedTest/java1 . Then I added the following code to
String sharedTestDir = 'src/sharedTest/java'
What it's doing above is adding my shared code directory to both the
androidTest source sets. Now, in addition to their default Java sources, they'll also include the shared code.
Voilà! Now both
androidTest can share utility code.
1 There's no particular reason the folder is called
sharedTest. It could be anything.