Espresso,Dagger2在BaseActivity上设置了ViemodelProvider.Factory

Tra*_*ace 14 android android-espresso dagger-2

我有一个像这样的抽象AccountRequiredActivity(并且工作正常):

public abstract class AccountRequiredActivity extends LifecycleActivity {

    @Inject
    ViewModelProvider.Factory viewModelFactory;

    private AccountViewModel accountViewModel;

    public abstract void doOnCreate(Bundle savedInstanceState);
    public abstract void doOnResume();

    @Override
    protected final void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading_app);
        AndroidInjection.inject(this);
        accountViewModel = ViewModelProviders.of(this, viewModelFactory).get(AccountViewModel.class);

        if(!accountViewModel.isAuthenticated()) {
            redirectToLogin();
        } else {
            doOnCreate(savedInstanceState);
        };

    }

    @Override
    protected void onResume() {
        super.onResume();
        if(!accountViewModel.isAuthenticated()) {
            redirectToLogin();
        } else {
            doOnResume();
        };
    }

    private void redirectToLogin() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }

}
Run Code Online (Sandbox Code Playgroud)

测试期间的问题是我没有办法设置viewModelFactory活动.

当一个活动有片段时,我可以做类似的事情:

@Before
public void init() {
    LoginFragment fragment = LoginFragment.newInstance();
    viewModel = mock(AccountViewModel.class);
    when(viewModel.getAuthenticatedUserResource()).thenReturn(authenticatedUser);

    fragment.viewModelFactory = ViewModelUtil.createFor(viewModel);
    activityRule.getActivity().setFragment(fragment);
}
Run Code Online (Sandbox Code Playgroud)

但是在这种情况下问题是我在我的测试中使用它(HomeActivity扩展了AccountRequiredActivity):

@Rule
public ActivityTestRule<HomeActivity> activityTestRule = new ActivityTestRule<>(HomeActivity.class, true, false);
Run Code Online (Sandbox Code Playgroud)

所以没有办法动态设置viewModelFactory,因为onCreate立即被调用.在onCreate调用之前似乎没有办法访问Activity对象.

如何解决这个问题?

注意:我使用Dagger 2.11和AndroidInjector.
另请参阅我昨天发布的关于后续信息的问题:

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

Tra*_*ace 1

我通过重写 AndroidInjector 的方法解决了这个问题inject()

@Override
public AndroidInjector<Activity> activityInjector() {
    return new AndroidInjector<Activity>() {
        @Override
        public void inject(Activity instance) {
            AccountViewModel viewModel = mock( AccountViewModel.class );
            if(instance instanceof TestHomeActivity) {
                ((TestHomeActivity) instance).viewModelFactory = ViewModelUtil.createFor( viewModel );
            }
        }
    };
} 
Run Code Online (Sandbox Code Playgroud)