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?
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:
This will press on the switch and turn it on (if it was off previously).