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.


enter image description here

1 Answers

VeeYik Pong On


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

class SampleSpinnerTest {

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

    fun clickSpinnerFirstItem() {