使用Dagger 2和自定义范围进行浓缩咖啡测试 [英] Espresso testing with Dagger 2 and custom scopes

查看:119
本文介绍了使用Dagger 2和自定义范围进行浓缩咖啡测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近迁移到Dagger 2后,我正在使用的应用程序对每个功能都使用@ActivityScope.每个应用程序功能都是使用MVP模式实现的,并且具有自己的本地匕首组件设置,在整个应用程序生命周期(由应用程序提供)中,依赖于应用程序组件的依赖关系取决于应用程序组件.每个功能的Activity扩展了一个基类,该基类将主要应用程序组件提供给每个活动都可以覆盖的方法,以设置本地匕首组件(构建本地组件并实例化本地模块).

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).

我要解决的问题是如何将模拟注入被测活动中.我遇到的主要问题是我无法在运行时将原始的本地组件和相应的模块与模拟的组件交换.我读过许多有关使用Dagger 2进行Espresso测试的文章,但它们并没有促进干净​​的体系结构.在大多数情况下,他们依靠AppComponent注入所有活动,在我的情况下,每个功能的组件都负责注入自己的活动.

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.

到目前为止,我想到的最好的方法是引入一个组件构建器,该构建器仅在测试设置中进行初始化,并在活动代码中进行初始化,以便与该设置一起进行;否则,请设置实际组件.但是,我不愿意将生产代码和测试代码混在一起. 这是代表Dagger设置的示意图: 匕首2设置

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

推荐答案

我最后采用的方法是按照

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).

为了保持主应用清单的整洁,在调试清单中声明了被覆盖的测试活动. 希望这种方法可以帮助具有类似我的Dagger 2设置的人进行测试浓咖啡和匕首2.

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.

有一个摇滚天!

这篇关于使用Dagger 2和自定义范围进行浓缩咖啡测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆