Espresso,Dagger2在BaseActivity上设置ViemodelProvider.Factory

时间:2017-10-01 14:27:13

标签: android dagger-2 android-espresso

我有一个像这样的抽象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);
    }

}

测试期间的问题是我无法在活动上设置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);
}

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

@Rule
public ActivityTestRule<HomeActivity> activityTestRule = new ActivityTestRule<>(HomeActivity.class, true, false);

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

如何解决这个问题?

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

Inject ViewModelFactory.Provider in activity for espresso testing

4 个答案:

答案 0 :(得分:0)

你可以创建自己的testrule

public class MyCustomRule<A extends MainActivity> extends ActivityTestRule<A> {
    public MyCustomRule(Class<A> activityClass) {
        super(activityClass);
    }

    @Override
    protected void beforeActivityLaunched() {
        super.beforeActivityLaunched();
        // Maybe prepare some mock service calls
        // Maybe override some depency injection modules with mocks
    }

    @Override
    protected Intent getActivityIntent() {
        Intent customIntent = new Intent();
        // add some custom extras and stuff
        return customIntent;
    }

    @Override
    protected void afterActivityLaunched() {
        super.afterActivityLaunched();
        // maybe you want to do something here 
    }

    @Override
    protected void afterActivityFinished() {
        super.afterActivityFinished();
        // Clean up mocks
    }
}

并设置为ActivityTestRule

@Rule
public ActivityTestRule<MainActivity> testRule = new MyCustomRule<>(MainActivity.class);

beforeActivityLaunched()中,您可以注入viewModelFactory

more here

答案 1 :(得分:0)

尝试覆盖dagger模块以提供ViewModelProvider.Factory。

  • 更改testInstrumentationRunner&#39; com.eusecom.attendance.MockTestRunner&#39;在app / build.gradle中

  • 在MockTestRunner中调用MockYourApplication.class

  • 在MockYourApplication.class中创建新的模拟匕首组件

  • 运行之前testActivity覆盖dagger组件和模块

观看示例https://github.com/eurosecom/Attendance/blob/master/app/src/androidTest/java/com/eusecom/attendance/DgAeaActivityTest.java

我没有使用带有AndroidInjector的新匕首2.11(我使用过较旧的dagger2模式),但可能有帮助。

答案 2 :(得分:0)

我通过重写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 );
            }
        }
    };
} 

答案 3 :(得分:0)

可以通过在@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);


}