简体   繁体   English

使用Dagger2在测试中注入模拟

[英]Injecting mocks in Tests using Dagger2

Say class A depends on B, and that I want to test class A. 说A类取决于B,并且我想测试A类。

I create a test for class A in which I want to mock B. 我为要模拟B的类A创建一个测试。

Class B is injected into class A using Dagger2 (using a Module and a Component). 使用Dagger2(使用模块和组件)将B类注入到A类中。 Meaning, class A has a class member: 意思是,A类有一个类成员:

@Inject
B mB;

In my test class, I create an instance of A in the setUp() method. 在测试类中,我在setUp()方法中创建A的实例。

How to I provide the mocked instance of the class B to A? 如何将类B的模拟实例提供给A?

You will need to provide a mock implementation using a mock build flavor if you normally inject your dependency with Dagger. 如果通常使用Dagger注入依赖项,则需要使用模拟构建风格提供模拟实现。 Usually this is done by replacing something like ProdModule with MockModule and then @Provides a mock implementation instead in your mock or test flavor. 通常,这是通过用MockModule替换ProdModule之类的东西来完成的,然后@Provid提供模拟实现,而不是模拟或测试形式。

Otherwise, a good testing option is Mockito if you want to guarantee that your mock returns what you want it to so that you don't have to worry about the mock implementation having a bug in it. 否则,如果您想保证您的模拟返回您想要的结果,那么一个不错的测试选项是Mockito,这样您就不必担心模拟实现中存在错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM