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 ?
One simple way to check for a View or its subclass like a Button is to use method getVisibility from View class.
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.
Espresso testing library extends the necessary JUnit classes to support the Android based instrumentation testing.
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());
}
}
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) {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With