简体   繁体   中英

not able to inject mock using Dagger

I am new to Dagger and Mockito. I am tring to use constructor defined in Dagger module in Unit test so the object is created with default values.

This is the Module:

@Module class AutoCloseCountDownTimerModule {

@Provides
@Singleton
fun getAutoCloseCountDownTimer(
    userInteractionClient: UserInteractionClient,
    rxPositionManager: RxPositionManager
): AutoCloseCountDownTimer {
    return AutoCloseCountDownTimer(userInteractionClient, rxPositionManager, 15000, 45000)
}

This is how I tried to Mock the AutoCloseCountDown class in unit test:

@RunWith(MockitoJUnitRunner.class) public class AutoCloseCountDownTimerTest {

@Mock
private AutoCloseCountDownTimer autoCloseCountDownTimer;

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
}

@Test
public void basicTest() {
    final AutoCloseCountDownTimer.Listener mockListener = Mockito.mock(AutoCloseCountDownTimer.Listener.class);
    autoCloseCountDownTimer.registerListener(mockListener);

    final int expectedValue = 10;
    autoCloseCountDownTimer.notifyOnAutoClose(expectedValue);
    Mockito.verify(mockListener).onAutoClose(expectedValue);

How can I achieve that the autoclosedCountDownTimer will be used in Test with values predefined by dagger?

You generally don't try to. In tests, you don't generally inject the parameters to the object under test, you pass them directly via new. Which can be regular or mock items.

If you do need to inject, you'd need to set up a module that provides the object via a function annotated with @Provides and that creates the mock and passes it into the parameter when instantiating the object.You'd also need to do this transitively with any dependencies that you aren't mocking out. Then create a component for that module and any others you need, and use that component to inject with. But you really want to avoid this if possible, unit tests should be about testing small pieces of functionality.

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