Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a RadioButton and selecting it in Espresso

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?

like image 581
Andrew W. Avatar asked Mar 20 '15 22:03

Andrew W.


2 Answers

Given the following layout:

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

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

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

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

</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!

like image 101
appoll Avatar answered Sep 30 '22 05:09

appoll


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()));
like image 20
Saurabh Pal Avatar answered Sep 30 '22 05:09

Saurabh Pal