Android. Espresso. How to click on Spinner item with text?
Asked Answered
T

3

9

I am trying to write a test that performs a click on a Spinner item by text.

My test contains these lines:

onView(withId(R.id.spn_trans_type))
    .perform(click());
onData(anything())
    .inAdapterView(withId(R.id.spn_trans_type))
    .onChildView(allOf(withId(textViewIdToTest), withText(expectedText)))
    .perform(click());

But I got an exception: NoMatchingViewException: No views in hierarchy found matching: with id: com.rirdev.aalf.demo:id/spn_trans_type

How to find spinner adapter view? In other words what should I put into inAdapterView() method ?

Trifle answered 5/1, 2016 at 19:20 Comment(0)
I
21

I've already found this answer:

Replace withText() with withSpinnerText()

onView(withId(spinnerId)).perform(click());
onData(allOf(is(instanceOf(String.class)), is(selectionText))).perform(click());
onView(withId(spinnerId)).check(matches(withSpinnerText(containsString(selectionText))));

Reference: https://code.google.com/p/android-test-kit/issues/detail?id=85

From: Android Espresso check selected spinner text

So instead of using a bit complicated:

onData(anything())
    .inAdapterView(withId(R.id.spn_trans_type))
    .onChildView(allOf(withId(textViewIdToTest), withText(expectedText)))
    .perform(click());

maybe you should use

onData(allOf(is(instanceOf(String.class)), is(selectionText)))
    .perform(click());
onView(withId(spinnerId))
    .check(matches(withSpinnerText(containsString(selectionText))));

where selectionText would be your expected string value and spinnerId an id of your Spinner view.

Indoiranian answered 5/1, 2016 at 22:29 Comment(0)
T
2

In my case, the simplest possible solution worked (Kotlin):

onView(withId(R.id.spinner)).perform(click())
onView(withText("Spinner Item 1")).perform(click());
Twinkle answered 16/7, 2020 at 14:10 Comment(0)
M
1

Just use this code:

ViewInteraction customTextView = onView(
                  allOf(withId(R.id.tv_spinner_desc), withText("hello"), isDisplayed()));
customTextView.perform(click());
Melantha answered 24/4, 2017 at 10:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.