Espresso testing with Dagger 2 and custom scopes

拥有回忆 提交于 2019-12-08 02:05:43

问题


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:


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!



来源:https://stackoverflow.com/questions/45176051/espresso-testing-with-dagger-2-and-custom-scopes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!