Inject ViewModelFactory.Provider in activity for espresso testing

后端 未结 1 1505
不思量自难忘°
不思量自难忘° 2021-01-14 00:54

Related to this question: Espresso, Dagger2 set ViemodelProvider.Factory on BaseActivity

I went through hell and back to get a ViewModelFactory.Provider on an Activi

相关标签:
1条回答
  • 2021-01-14 01:35

    It’s possible to set injected activity attribute by registering a custom ActivityLifecycleCallbacks in your TestApp in the @Before Method.

    Example:

     @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);
    
    
    }
    
    0 讨论(0)
提交回复
热议问题