【问题标题】:Testing a Fragment's onCreate method with a savedInstanceState Bundle in Robolectric?在 Robolectric 中使用 savedInstanceState Bundle 测试 Fragment 的 onCreate 方法?
【发布时间】:2013-12-31 02:54:58
【问题描述】:

我有一个带有 onCreate 方法的 Fragment,它使用传入的 savedInstanceState Bundle 做一些事情。我正在使用 Robolectric 创建一个 Activity 并使用 Activity 的 FragmentManager 启动 Fragment。

我遇到的问题是我不知道如何从测试代码中插入一个 savedInstanceState Bundle 来验证使用它的代码路径。

我希望 Robolectric 有一个影子片段,可以让我直接设置捆绑包。

有什么想法吗?

【问题讨论】:

  • 您使用哪个 Robolectric 版本?

标签: android testing android-fragments robolectric


【解决方案1】:

如果您使用 Robolectric 2.x,那么您可以将 Bundle 传递给活动:

Bundle savedBundle = new Bundle();

activity = buildActivity( FragmentActivity.class ).create( savedBundle ).start().resume().get();

MyFragment fragment = new MyFragment();

FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add( fragment, null );
fragmentTransaction.commit();

【讨论】:

  • 这对我不起作用。我传入了一个包,但是在我的片段上调用 ​​onCreate 时,savedInstanceState 包始终为空。
【解决方案2】:

我刚刚使用反射并将包私有字段 mSavedFragmentState 设置为我想要接收的捆绑包。

    Fragment fragment = new YourFragment();
    Bundle bundle = new Bundle();

    Field field = Fragment.class.getDeclaredField("mSavedFragmentState");
    field.setAccessible(true);
    field.set(fragment, bundle);

    SupportFragmentTestUtil.startFragment(fragment);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 2014-11-12
    相关资源
    最近更新 更多