Search code examples
androidautomated-testsandroid-espressoui-testing

Espresso always fails when trying to select item in spinner


I tried to select an item from a simple spinner, but it always failed. I can click the spinner and it shows the list. But when I try to select even the first option, it always throw indexOutOfBoundsException:

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at android.widget.ArrayAdapter.getItem(ArrayAdapter.java:385)
at android.widget.Spinner$DropDownAdapter.getItem(Spinner.java:1010)
at android.widget.AdapterView.getItemAtPosition(AdapterView.java:801)
at androidx.test.espresso.action.AdapterViewProtocols$StandardAdapterViewProtocol.getDataInAdapterView(AdapterViewProtocols.java:90)
at androidx.test.espresso.action.AdapterDataLoaderAction.perform(AdapterDataLoaderAction.java:79)
at androidx.test.espresso.ViewInteraction$SingleExecutionViewAction.perform(ViewInteraction.java:360)
at androidx.test.espresso.ViewInteraction.doPerform(ViewInteraction.java:251)
at androidx.test.espresso.ViewInteraction.access$100(ViewInteraction.java:64)
at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:157)
at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:154)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:101)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7529)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)

Tests ran to completion.

I tried some methods (this, this) with the same result. Here's my current implementation:

        onView(withId(R.id.spinner)).perform(click())
        Thread.sleep(7000)

        onData(allOf(`is`(instanceOf(String::class.java)))).atPosition(0).perform(click())
        Thread.sleep(7000)
        onView(withId(R.id.selected)).check(matches(withText(instanceForTest)))

Solution

  • I ended up using the id and the text in the textView:

    try {
    
        Thread.sleep(3000)
    
        onView(withId(R.id.spinner))
                .perform(click())
    
        onView(allOf(withId(R.id.text_name), withText(instanceForTest)))
                .perform(scrollTo(), click())
    
        onView(withId(R.id.text_name))
                .check(matches(withText(instanceForTest)))
    
        Thread.sleep(3000)
    
        onView(withId(R.id.start)).perform(click())
    
    } catch (e: NoMatchingViewException) {
    
    }
    

    It might not the best way, but this one works.