I want to select the first item in a ListView with Expresso. I can't target by text because the list always changes. As well, all items in the list have the same ID and are not unique. I have attached a screenshot of how this view looks. How do I target and click on the item in the first position with expresso?

I have tried onView(withId(R.id.tv_default_spinner)).performClick() but will get the exception that there are multiple items with the same id.

TIA

enter image description here

1 Answers

0
VeeYik Pong On

Edited:

Find the type of the class with Matchers.allOf and Matchers.instanceOf, and click on the position you desired.

I have tested this in one of my Kotlin project and it is working.

Can refer to the code below, I clicked on first item (position 0)

import androidx.test.espresso.Espresso
import androidx.test.espresso.Espresso.onData
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.matcher.ViewMatchers
import androidx.test.rule.ActivityTestRule
import androidx.test.runner.AndroidJUnit4
import org.hamcrest.Matchers.allOf
import org.hamcrest.Matchers.instanceOf
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith

@RunWith(AndroidJUnit4::class)
class SampleSpinnerTest {

    @Rule
    @JvmField
    var mActivityRule = ActivityTestRule(MainActivity::class.java, false)

    @Test
    fun clickSpinnerFirstItem() {

        Espresso.onView(ViewMatchers.withId(R.id.spinner_data)).perform(ViewActions.click());

        onData(allOf(instanceOf(String::class.java))).atPosition(0).perform(ViewActions.click())
    }
}