Espresso testing with Dagger 2 and custom scopes

716 views Asked by At

After a recent migration to Dagger 2, the app I am working on is using an @ActivityScope for every feature. Each app feature is implemented using MVP pattern and has it's own local dagger Component setup which depends on the Application component for the dependencies that are required during the entire app lifecycle (provided by the App). Each feature’s Activity extends a base class which provides the main application component to a method that is overridden by each activity in order to set up the local dagger component (builds the local component and instantiates the local module).

The issue I am trying to solve is how to inject mocks into the Activity under test. The main problem I am experiencing is that I cannot swap the original local component and corresponding module with mocked ones at runtime. There are many articles on Espresso testing with Dagger 2 that I read, but they are not promoting clean architecture. For the most part they rely on the AppComponent to inject all Activities, where in my case, each feature’s component is responsible for injecting it’s own activity.

So far the best approach that I came up with was to introduce a component builder that is only initialised as part of the test setup and in the Activity code to go with this setup if initialised, otherwise set up the real component. However, I am reluctant to mix production and test code. Here is a schematic which represents the Dagger setup: Dagger 2 Setup

1

There are 1 answers

0
The Riddler On

The approach that I took at the end was to create a custom AndroidJUnitRunner as described here and to create Components/Modules which provide mocks for each app feature, including the Application module check Google doc for best practices. Furthermore, each activity under test has to be overridden to inject the mocks (just the method that injects the mocked dependencies).

In order to keep the main app manifest clean, the overridden test activities are declared in a debug manifest. Hope this approach helps people with a similar to my Dagger 2 setup to do their testing with Espresso and Dagger 2.

Have a rock ’n’ roll day!