In 2015, I wrote a post about sharing code between unit tests and instrumentation tests on Android. Iain Cunningham just pointed out that the method I outlined no longer works.
That’s fine for me because I haven’t used that method in years! Nowadays I use modules, which provide a far superior method of solving the problem (and is the method Google promotes now as well). Here’s how that works:
- Start with a module called
- Create a second module named
:libraryas a dependency of it.
- Implement your shared test utilities in
- Now, here’s the trick: add
:library-shared-testas a dependency to your tests in
Even though it seems like you’re creating a circular dependency in step four, you’re not. Instead, you’re creating a dependency chain from
I’ve put up a demonstration project here if that helps your understanding.
There is one huge advantage this method has over the old one: any module can use
:library-shared-test now. If
:library-shared-test contains useful utilities or fakes, then anyone consuming
:library can also test using those now, too.
It should be fairly painless to go from the old method to the new one, and you get some bonuses along the way. Go for it!
Edit: After publishing, Zac Sweers pointed out to me that there's a Gradle test fixtures plugin which basically does the same thing as outlined above, but better. It doesn't work on Kotlin Android projects yet, so the advice above is still good for now, but for non-kotlin-android projects you should probably use that instead.