Android Mocking a Dagger2 injected dependency for a Espresso test

后端 未结 3 1960
太阳男子
太阳男子 2021-02-15 11:40

I have a heavily dependency injected (dagger2) application. I would like to run an espresso test without having the test navigate through the whole application

3条回答
  •  温柔的废话
    2021-02-15 12:36

    First, your decision to use dependency injection (Dagger2) is a very good one and will indeed make your tests easier to write.

    You have to override dependency injection configuration (module) and inject a mock. Here is a simple example of how it can be done.

    First you need a mock:

    LoginStateManager lsmMock = mock(LoginStateManager.class);
    

    Now override the DI config to use this mock:

    //Extend your TelePresenterModule, override provider method
    public class TestTelePresenterModule extends TelePresenterModule{
        @Override
        public LoginStateManager getLoginStateManager() {
            //simply return the mock here
            return lsmMock;
        }
    }
    

    Now to the test:

    @Test
    //this is an espresso test
    public void withAMock() {
        //build a new Dagger2 component using the test override
        TelePresenterComponent componentWithOverride = DaggerTelePresenterComponent.builder()
                //mind the Test in the class name, see a class above
                .telePresenterModule(new TestTelePresenterModule())
                .build();
    
        //now we initialize the dependency injector with this new config
        DaggerInjectorTele.set(componentWithOverride);
    
        mActivityRule.launchActivity(null);
    
        //verify that injected mock was interacted with
        verify(lsmMock).whatever();
    }
    

    Example from: https://github.com/yuriykulikov/DIComparison/blob/master/app/src/androidTest/java/com/example/yuriy/dependencyinjectioncomparison/Dagger2Test.java

提交回复
热议问题