Sharing code between test modules

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:

  1. Start with a module called :library.
  2. Create a second module named :library-shared-test and put :library as a dependency of it.
  3. Implement your shared test utilities in :library-shared-test.
  4. Now, here’s the trick: add :library-shared-test as a dependency to your tests in :library.

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 :library -> :library-shared-test -> :library’s tests.

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.