Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use espresso matcher as a condition for If else statement?

The snippet of my code looks like this:

private void SelectOnline(String env) {    
     onView(withText("Some Text")).perform(click());

     if (onView(withText(env)).check(matches(isChecked()))) {
           onView(withId(R.id.dialogCancel)).perform(click());
     }else {
           onView(withText(env)).perform(click());
     }
}

I got an error with message

required: boolean
found: ViewInteraction

This means that you cannot use espresso View Matchers as a condition for if..else. Is there some other way to implement if..else statement ?

like image 512
blues Avatar asked Aug 11 '15 15:08

blues


People also ask

How do you check espresso visibility?

One simple way to check for a View or its subclass like a Button is to use method getVisibility from View class.

How do you assert espresso?

check is a method which accepts an argument of type ViewAssertion and do assertion using passed in ViewAssertion object. matches(withText(“Hello”)) returns a view assertion, which will do the real job of asserting that both actual view (found using withId) and expected view (found using withText) are one and the same.

Which is the class used in espresso framework to identify mobile test objects?

Espresso testing library extends the necessary JUnit classes to support the Android based instrumentation testing.


2 Answers

Espresso was designed in a way to discourage devs from using conditionals, so there's no officially supported way to do this.

However, there are hacks you can try. I use try/catch statements. In your case, it would be something along the lines of:

private void SelectTransitBackendOnline(String env) {    
     onView(withText("Some Text")).perform(click());

     try {
           onView(withText(env)).check(matches(isChecked())))
           onView(withId(R.id.dialogCancel)).perform(click());
     } catch (AssertionFailedError e) {
           onView(withText(env)).perform(click());
     }
}
like image 140
Tin Man Avatar answered Sep 27 '22 21:09

Tin Man


Depending on what you are doing in the try block, change the catch block's exception. I wanted to click on cancel_button if it exists, so I changed it to:

try {
    onView(withId(R.id.cancel_button)).perform(click());
} catch (NoMatchingViewException ignore) {
}
like image 32
Zahra Jamshidi Avatar answered Sep 27 '22 21:09

Zahra Jamshidi