如何使用 Espresso 测试片段

新手上路,请多包涵

我有一个要测试的 Android 片段。我创建了一个测试活动,我将这个片段添加到其中并运行一些 Espresso 测试。

但是,Espresso 在片段中找不到任何视图。它转储视图层次结构,它是空的。

我不想使用实际的父活动。我只想单独测试这个片段。有没有人这样做过?是否有具有类似代码的示例?

 @RunWith(AndroidJUnit4.class)
class MyFragmentTest {
    @Rule
    public ActivityTestRule activityRule = new ActivityTestRule<>(
    TestActivity.class);

    @Test
    public void testView() {
       MyFragment myFragment = startMyFragment();
       myFragment.onEvent(new MyEvent());
       // MyFragment has a recyclerview.
       //OnEvent is EventBus callback that in this test contains no data.
       //I want the fragment to display empty list text and hide the recyclerView
       onView(withId(R.id.my_empty_text)).check(matches(isDisplayed()));
       onView(withId(R.id.my_recycler)).check(doesNotExist()));
    }

    private MyFragment startMyFragment() {
         FragmentActivity activity = (FragmentActivity) activityRule.getActivity();
    FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
    MyFragment myFragment = new MyFragment();
    transaction.add(myFragment, "myfrag");
    transaction.commit();
    return myFragment;
    }
}

原文由 greenrobo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 284
1 个回答

我将按照以下方式创建一个 ViewAction,如下所示:

 public static ViewAction doTaskInUIThread(final Runnable r) {
    return new ViewAction() {
        @Override
        public Matcher<View> getConstraints() {
            return isRoot();
        }

        @Override
        public String getDescription() {
            return null;
        }

        @Override
        public void perform(UiController uiController, View view) {
            r.run();
        }
    };
}

然后使用下面来启动应该在 UI 线程中运行的代码

onView(isRoot()).perform(doTaskInUIThread(new Runnable() {
        @Override
        public void run() {
            //Code to add your fragment or anytask that you want to do from UI Thread
        }
    }));

下面是一个测试用例添加片段视图层次结构的例子

    @Test
public void testSelectionOfTagsAndOpenOtherPage() throws Exception{

    Runnable r = new Runnable() {
        @Override
        public void run() {
            //Task that need to be done in UI Thread (below I am adding a fragment)

        }
    };
    onView(isRoot()).perform(doTaskInUIThread(r));

}

原文由 Ankur 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题