尝试 select 微调器中的项目时,Espresso 总是失败

Espresso always fails when trying to select item in spinner

我尝试 select 来自简单微调器的项目,但总是失败。我可以单击微调器,它会显示列表。但是当我尝试 select 即使是第一个选项时,它总是抛出 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.access0(ViewInteraction.java:64)
at androidx.test.espresso.ViewInteraction.call(ViewInteraction.java:157)
at androidx.test.espresso.ViewInteraction.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.

我尝试了一些方法(this, ),结果相同。这是我当前的实现:

        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)))

使用咖啡师的方法clickSpinnerItem(R.id.spinner, indexToSelect)。它适用于各种数据,无论是哪种数据。此外,您的测试将更具可读性。从 https://github.com/SchibstedSpain/Barista

获取咖啡师

顺便说一下,考虑使用 Barista 的 sleep 方法,或者如果可能的话,实现您自己的 IdlingResource 以使您的测试更快更可靠。

我最终在 textView 中使用了 id 和文本:

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) {

}

这可能不是最好的方法,但这个方法很有效。