gpt4 book ai didi

android - 在 Activity 中注入(inject) ViewModelFactory.Provider 以进行浓缩咖啡测试

转载 作者:太空宇宙 更新时间:2023-11-03 11:23:58 25 4
gpt4 key购买 nike

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

在我的测试期间,为了让 espresso 测试在 Android 架构组件上工作,我经历了 hell 并返回到 Activity 上的 ViewModelFactory.Provider。我原以为它很简单,但我想它不是......

使用 fragment 的示例很简单:
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);
}

但是,这根本不适用于 Activity ,因为我无法在 Activity 创建之前使用 ActivityTestRule 获取 Activity 的依赖项。
我使用 Dagger2 遵循与上面示例中相同的新依赖项注入(inject)流程,使用 HasActivityInjector 接口(interface)。

非常感谢您的帮助!

最佳答案

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

例子:

 @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);


}

关于android - 在 Activity 中注入(inject) ViewModelFactory.Provider 以进行浓缩咖啡测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46533989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com