首页 > 解决方案 > 如何使用recyclerview单击项目操作为片段容器编写浓缩咖啡测试用例

问题描述

我有一个活动,它有一个片段容器,它用 recyclerview 加载一个片段。单击任何回收站视图项目时,它将打开一个新活动。我想为这种情况编写一个浓缩咖啡测试用例。

我的活动:

<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/background">

<FrameLayout
    android:id="@+id/fragmentContainer"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:orientation="vertical"
    android:layout_weight="1">

</FrameLayout>

我的片段 xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="16dp"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_items"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

我的测试案例:

@RunWith(AndroidJUnit4.class)
public class MainActivityTest {

    @Rule
    public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);

    @Before
    public void init() {
        mActivityTestRule.getActivity()
                .getSupportFragmentManager().beginTransaction();
    }

    @Test
    public void recyclerview_clickTest() {
       /* onView(withId(R.id.fragmentContainer)).perform(RecyclerViewActions.actionOnItemAtPosition(0, click()));
        onView(withText("Alpha")).perform(click());
        onView(allOf(instanceOf(TextView.class), withParent(withResourceName("action_bar"))))
                .check(matches(withText("Alpha")));*/

        onData(allOf(is(new BoundedMatcher<Object, MyModel>(MyModel.class) {
            @Override
            public void describeTo(Description description) {
            }
            @Override
            protected boolean matchesSafely(MyModel abc) {
                return onView(allOf(instanceOf(TextView.class), withParent(withResourceName("action_bar"))))
                        .check(matchesSafely(withResourceName(abc)));
            }
        })));
    }
}

TIA。

标签: androidandroid-recyclerviewandroid-espresso

解决方案


您可以使用 ViewMatchers 进行此操作

例子

onView(withId(R.id.your_recycler_view)).perform(RecyclerViewActions.actionOnItemAtPosition(0, click()));

推荐阅读