Accessing a RadioButton and selecting it in Espres

2019-06-20 23:54发布

I am using Espresso to test an Android application. I am having trouble trying to find a way to access and select a RadioButton (which belongs to a RadioGroup) of the current Activity. Does anyone have any suggestions? Thanks you

-Andrew

2条回答
相关推荐>>
2楼-- · 2019-06-21 00:24

Given the following layout:

<RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/radioGroup"
        >

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/first_radio_button"
            android:id="@+id/firstRadioButton"
            />

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/second_radio_button"
            android:id="@+id/secondRadioButton"
            />

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/third_radio_button"
            android:id="@+id/thirdRadioButton"
            />

    </RadioGroup>

Write a new test method with the following:

        onView(withId(R.id.firstRadioButton))
                .perform(click());

        onView(withId(R.id.firstRadioButton))
                .check(matches(isChecked()));

        onView(withId(R.id.secondRadioButton))
                .check(matches(not(isChecked())));

        onView(withId(R.id.thirdRadioButton))
                .check(matches(not(isChecked())));

Voila!

查看更多
甜甜的少女心
3楼-- · 2019-06-21 00:48

for the above solution, if "not" is not resolvable use "isNotChecked" in place of "(not(isChecked()))"

    onView(withId(R.id.firstRadioButton))
            .perform(click());

    onView(withId(R.id.firstRadioButton))
            .check(matches(isNotChecked()));

    onView(withId(R.id.secondRadioButton))
            .check(matches(isNotChecked())));

    onView(withId(R.id.thirdRadioButton))
            .check(matches(isNotChecked()));
查看更多
登录 后发表回答