我有一个要测试的 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 许可协议
我将按照以下方式创建一个 ViewAction,如下所示:
然后使用下面来启动应该在 UI 线程中运行的代码
下面是一个测试用例添加片段视图层次结构的例子