Unable to click on SwitchPreference with Espresso Ui Test (Android)

348 Views Asked by At

I am having one SwitchPreference (PreferenceFragmentCompat) and wanted to click on the toggle button. But I am unable to do so.

Here’s my code:

@Test
fun settings_testSwitch() {
    pressAudioOnlyToggle()
}
fun pressAudioOnlyToggle() {
    onData(allOf(`is`(instanceOf(Preference::class.java)), withText(“Audio only"))).perform(click())
}

I am getting one error like the following:

androidx.test.espresso.NoMatchingViewException: No views in hierarchy found matching: is assignable from class: class android.widget.AdapterView

Any idea how to solve it?

1

There are 1 best solutions below

1
Sayan Subhra Banerjee On BEST ANSWER

As you are using PreferenceFragmentCompat, so you need to pass recycler_view as the id, because PreferenceFragmentCompat uses a RecyclerView internally. And then you need to use RecyclerViewActions.actionOnItem.

Let’s look at the code below:

fun pressAudioOnlyToggle() {
    Espresso.onView(ViewMatchers.withId(androidx.preference.R.id.recycler_view))
    .perform(
        RecyclerViewActions.actionOnItem<RecyclerView.ViewHolder>(
            ViewMatchers.hasDescendant(ViewMatchers.withText("Audio only")),
            ViewActions.click()
        )
    )
}

This will press on the switch and turn it on (if it was off previously).