android - 如何使用 Espresso 测试 fragment

标签 android android-espresso

我有一个要测试的 Android fragment 。我创建了一个测试 Activity ,我向其中添加了这个 fragment 并运行了一些 Espresso 测试。

但是,Espresso 在 fragment 中找不到任何 View 。它会转储 View 层次结构,并且全部为空。

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

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

最佳答案

我会按照以下方式做 创建一个 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
        }
    }));

下面是添加 fragment View 层级的测试用例示例

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

}

关于android - 如何使用 Espresso 测试 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35471425/

相关文章:

android - Java.util.zip.ZipException : duplicate entry: com/google/common/base/FinalizableReference. 类

有两个 fragment 的安卓

android - 在openGL android中将图像纹理渲染到立方体贴图中

android - 使用 SpeechRecognizer API 对 editText 进行语音输入的 Espresso 测试

Android Espresso 测试永远不会完成

android - 使用 android espresso 测试具有多个 fragment 的 ViewPager

java - Espresso 不等待键盘打开

android - 当您从 Wifi 切换到移动数据时,您的手机 IP 地址是否会发生变化?

android - 为以编程方式创建的编辑文本执行类型文本

android - 新 gradle 和 android sdk 版本的 Roboelectric 问题