在espresso测试活动中注入ViewModelFactory.Provider

时间:2017-10-02 21:29:03

标签: android dagger-2

与此问题相关:Espresso, Dagger2 set ViemodelProvider.Factory on BaseActivity

我在测试期间经历了地狱并返回以获取活动上的ViewModelFactory.Provider,以便让espresso测试与Android架构组件相关。我希望它很简单,但我想这不是......

使用碎片处理它的例子非常简单:
https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/src/androidTest/java/com/android/example/github/ui/user/UserFragmentTest.java

@Before
public void init() {
    UserFragment fragment = UserFragment.create("foo");
    viewModel = mock(UserViewModel.class);
    when(viewModel.getUser()).thenReturn(userData);
    when(viewModel.getRepositories()).thenReturn(repoListData);
    navigationController = mock(NavigationController.class);
    fragmentBindingAdapters = mock(FragmentBindingAdapters.class);

    fragment.viewModelFactory = ViewModelUtil.createFor(viewModel);
    fragment.navigationController = navigationController;
    fragment.dataBindingComponent = () -> fragmentBindingAdapters;

    activityRule.getActivity().setFragment(fragment);
}

但是,这根本不适用于活动,因为我无法在使用ActivityTestRule创建活动之前获取活动的依赖关系。
我使用HasActivityInjector接口按照上面示例中的Dagger2执行相同的新依赖注入流程。

感谢您的帮助!

1 个答案:

答案 0 :(得分:-1)

可以通过在@Before方法中的TestApp中注册自定义ActivityLifecycleCallbacks来设置注入活动属性。

示例:

 @Before
public void init(){


    UserFragment fragment = UserFragment.create("foo");
    viewModel = mock(UserViewModel.class);
    when(viewModel.getUser()).thenReturn(userData);
    when(viewModel.getRepositories()).thenReturn(repoListData);
    navigationController = mock(NavigationController.class);


    TestApp testApp = ((TestApp) InstrumentationRegistry.getContext().getApplicationContext());
    testApp.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            //will be called before the onCreate method of your activity
            activity.setViewModelFactory(ViewModelUtil.createFor(viewModel));
        }

        @Override
        public void onActivityStarted(Activity activity) {

        }

        @Override
        public void onActivityResumed(Activity activity) {

        }

        @Override
        public void onActivityPaused(Activity activity) {

        }

        @Override
        public void onActivityStopped(Activity activity) {

        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

        }

        @Override
        public void onActivityDestroyed(Activity activity) {

        }
    });


    fragment.viewModelFactory = ViewModelUtil.createFor(viewModel);
    fragment.navigationController = navigationController;
    fragment.dataBindingComponent = () -> fragmentBindingAdapters;

    activityRule.getActivity().setFragment(fragment);


}