简体   繁体   中英

Injecting mocks in Tests using Dagger2

Say class A depends on B, and that I want to test class A.

I create a test for class A in which I want to mock B.

Class B is injected into class A using Dagger2 (using a Module and a Component). Meaning, class A has a class member:

@Inject
B mB;

In my test class, I create an instance of A in the setUp() method.

How to I provide the mocked instance of the class B to A?

You will need to provide a mock implementation using a mock build flavor if you normally inject your dependency with 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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