Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 595
IgorOK Avatar asked Jan 05 '16 19:01

IgorOK


2 Answers

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.

like image 110
piotrek1543 Avatar answered Oct 17 '22 13:10

piotrek1543


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

onView(withId(R.id.spinner)).perform(click())
onView(withText("Spinner Item 1")).perform(click());
like image 38
voghDev Avatar answered Oct 17 '22 13:10

voghDev