Mock injected ViewModel

蓝咒 提交于 2019-12-12 05:48:50

问题


I need to run Android instrumented test on StarterActivity. Here is how it goes

public class StarterActivity extends BaseActivity<ActivityStarterBinding> {

    @Inject
    protected StarterViewModel starterViewModel;

    @Override
    public int getContentView() {
        return R.layout.activity_starter;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getApplicationComponent().inject(this);
    }
    //...
}

And I call for starterViewModel method in onStart.

StarterViewModel is injected via a constructor:

public class StarterViewModel {

    private final AuthDataModel authDataModel;

    @Inject
    public StarterViewModel(AuthDataModel authDataModel) {
        this.authDataModel = authDataModel;
    }

    @NonNull
    public Single<Boolean> isUserLoggedIn() {
        return authDataModel.isUserLoggedIn();
    }
}

I found this really nice approach Android testing using Dagger 2, Mockito and a custom JUnit rule. But it needs me to add @Provide method. And application component is going to become "God component" with dependencies on a bunch of Modules (or one "God module").

How can I mock in Espresso test without adding @Provide method and overriding it in tests?

来源:https://stackoverflow.com/questions/45166990/mock-injected-viewmodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!