android - 在 robolectric 的单元测试期间获取空指针异常

标签 android robolectric

我有按钮点击监听器,其点击 fragment 被替换,并在下一个 fragment 上传递参数。 代码:-

 Fragment fragment = new CustomList();
            Bundle args = new Bundle();
            args.putString("fragment", "Custom");
            args.putSerializable("productBean", productBean);
            fragment.setArguments(args);
            fragmentManager = getActivity().getSupportFragmentManager();
            fragmentTransaction = fragmentManager
                    .beginTransaction();
            fragmentTransaction.setCustomAnimations(R.anim.slide_in, R.anim.slide_out, R.anim.slide_enter, R.anim.slide_exit);
            fragmentTransaction.replace(R.id.container_body, fragment);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();

按钮点击的书面测试用例:-

Button custom_btn = (Button) fragment.getView().findViewById(R.id.custom_btn);
             custom_btn.performClick();

但是在执行测试用例时,在 CustomList() fragment 上获取参数时显示空指针异常。

productsBean = (ProductsBean) getArguments().getSerializable("productsBean");

最佳答案

尝试更改此代码:

productsBean = (ProductsBean) getArguments().getSerializable("productsBean");

对此

productsBean = (ProductsBean) getArguments().getSerializable("productBean");

如您所见,您正在向包中添加标签 "productBean",但是当您尝试获取它时,您使用的是标签 "productsBean",您在其中添加了“s”字符。

我会从那个改变开始。

关于android - 在 robolectric 的单元测试期间获取空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43472427/

相关文章:

android - VideoView内的YouTube RTSP URL播放-低质量

android - Cordova问题无法添加平台android

java - 为什么在使用 Robolectric 的 Android 单元测试中调用 HtmlCompat 时会出现 ExceptionInInitializerError?

android - 如何对android的http请求进行单元测试

android - 与 Robolectric 一起运行时 Mockito 测试中的 SecurityProvider

android - 加载上次运行的数据

android - HardwareRenderer createSurface 上的 IllegalStateException

未找到 AndroidHttpClient(运行 Robolectric 时)

android - 让 Mockito 与 RoboGuice 和 Robolectric 一起工作

android - 如何从 Activity 返回到上一个 fragment ?