Android模拟Dagger2注入的依赖项以进行Espresso测试 [英] Android Mocking a Dagger2 injected dependency for a Espresso test

查看:162
本文介绍了Android模拟Dagger2注入的依赖项以进行Espresso测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个严重依赖注入的( dagger2 )应用程序.我想运行 espresso测试,而无需测试在整个应用程序中导航并登录到该应用程序.

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, and log into the application.

我想从我的teleActivity开始,并模拟登录管理器.但是,在任何@test函数中,我们已经按调用onCreate的方式命中了null指针.如果我在启动活动之前覆盖它(如下所示),则该活动为null.

I would like to start on my teleActivity, and mock the login manager. However in any @test function, we have already hit the null pointer as we have called onCreate. If I override it before we launch the activity (show below) the activity is null.

据我所知,切换下划线依赖性的能力是我们使用Dagger2的主要原因,否则将是过度设计的单例.如何覆盖,模拟或将注入切换到测试匕首模块-这样我就可以创建此简单的意式浓缩咖啡测试.

To my understanding, the ability to switch our underlining dependencies is a large reason why we use Dagger2, else it would be just a very over engineered singleton. How do I override, mock, or switch the injection to a testing dagger module -- so I can create this simple espresso test.

请注意,如果有区别的话,我也会在MVP设计模式中编写所有这些内容.

Note I also wrote all this in the MVP design pattern if that makes a difference.

TeleActivity

TeleActivity

@Inject
TelePresenter mTelePresenter;
@Inject
public LoginStateManager mLoginStateManager;

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ButterKnife.bind(this);
    DaggerInjectorTele.get().inject(this);
    mTelePresenter.setTeleDependencies(this);
    Intent intent = getIntent();

    String searchId = null;

    if (intent != null) {
        searchId = intent.getStringExtra(Constants.SEARCH_ID);
       }

    mTelePresenter.onCreateEvent(searchId,
            Helper.makeAuthorizationHeader(
            // CRASH Null pointer
            mLoginStateManager.getBaseLoginResponse().getAccessToken()));

}

浓咖啡

@LargeTest
@RunWith(AndroidJUnit4.class)
public class TeleTest {
    @Rule
    public ActivityTestRule<TeleActivity> mActivityTestRule = new ActivityTestRule(
            TeleActivity.class) {
        @Override
        protected void beforeActivityLaunched() {
            super.beforeActivityLaunched();
            TeleActivity teleActivity = (TeleActivity)getActivity();
             //teleActivity NULL!
            teleActivity.mLoginStateManager = mock(LoginStateManager.class);
            LoginResponse loginResponse = mock(LoginResponse.class);
            when(loginResponse.getAccessToken()).thenReturn("1234");
            // Nope here still null


when(teleActivity.mLoginStateManager.getBaseLoginResponse()).thenReturn(loginResponse);

        }
    };

匕首注射器

  public class DaggerInjectorTele {
    private static TelePresenterComponent telePresenterComponent =
            DaggerTelePresenterComponent.builder().build();

    public static TelePresenterComponent get() {
        return telePresenterComponent;
    }
}

TelePresenterComponent

TelePresenterComponent

@Singleton
@Component(modules = {TelePresenterModule.class,
        LoginStateManagerModule.class})
public interface TelePresenterComponent {
    void inject(TeleActivity activity);
}

TelePresenterModule

TelePresenterModule

@Module
public class TelePresenterModule {

    @Provides
    @Singleton
    public TelePresenter getTelePresenter() {
        return new TelePresenter();
    }
}

LoginStateManagerModule

LoginStateManagerModule

@Module
public class LoginStateManagerModule {

    @Provides
    @Singleton
    public LoginStateManager getLoginStateManager(){
        return new LoginStateManager();
    }
}

推荐答案

首先,您决定使用依赖注入(Dagger2)是一个很好的决定,确实会使您的测试更易于编写.

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

现在覆盖DI配置以使用此模拟程序:

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;
    }
}

现在要测试:

@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();
}

来自以下示例: 查看全文

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