Modern Android development often involves modularization to enhance build performance and maintainability. As you break down your app into multiple modules, sharing test utilities such as fixtures, mocks, or fakes between modules can become challenging. A few years ago I wrote about the concept of test fixtures, but at the time they weren’t supported for Android modules. Thankfully, with Android Gradle Plugin (AGP) 8.5.0, Google introduced native support for test fixtures, streamlining this process significantly.
What Are Test Fixtures?
Test fixtures are reusable components such as test data, helper classes, or mocks that you can use to support your tests. Prior to AGP 8.5.0, sharing these utilities across modules often required workarounds like creating dedicated “test” modules or manually wiring dependencies. With AGP 8.5.0, the testFixture
s feature makes it easier to declare and consume test fixtures directly from your modules.
Setting Up Test Fixtures
To enable test fixtures for a module, you need to include the testFixtures
feature in your module’s build.gradle.kts
file. Here’s how you can set it up:
1 2 3 4 5 6 7 8 9 |
|
The testFixtures source set is automatically created under the src directory:
1 2 3 4 5 6 7 8 9 |
|
You can now place reusable test utilities, such as mock data generators or fake implementations, inside the testFixtures
directory.
Consuming Test Fixtures
Modules can consume test fixtures by declaring a dependency on the testFixtures
configuration of another module. For example, if module-b
needs to use the test fixtures from module-a
, add the following dependency:
1 2 3 |
|
Once this dependency is added, the test code in module-b can seamlessly access the fixtures provided by module-a
.
Example: Sharing a Fake API Client
Suppose you have a fake API client used in multiple test cases. You can define it in the testFixtures
source set of module-a
:
1 2 3 4 5 6 |
|
Then, in module-b
, you can consume and use this fake client:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Conclusion
The testFixtures feature in AGP 8.5.0 is a game-changer for modularized Android projects. It eliminates the friction of sharing test utilities, allowing you to write cleaner, more maintainable test setups. If you’re working on a modularized project and haven’t tried testFixtures yet, now is the perfect time to incorporate it into your testing strategy.