Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: Include shorthand fluent functions to more closely match idiomatic Espresso #7

Open
freakingawesome opened this issue Jan 4, 2018 · 0 comments

Comments

@freakingawesome
Copy link

Thanks for ConditionWatcher! It really helped get me away from littering production code with references to Idling Resources.

In our project (which uses Kotlin), we've added some helper functions to allow us to tie directly into Espresso's functions so that we can mimic the withId() and .check(matches(...)) syntax. This allows us to do this:

waitForView(withId(R.id.searchfield_clearbutton)).toMatch(allOf(isDisplayed(), isEnabled()))

This eliminates the need for having to deal with activity or test context, and the implementation is fairly trivial (again, this is Kotlin):

/**
 * Waits for the view specified by the matcher meats the specified condition
 */
fun waitForView(viewMatcher: Matcher<View>) = ViewMatcherWaiter(viewMatcher)

/**
 * Used by the waitForView() shorthand fluent function
 */
class ViewMatcherWaiter constructor(val viewMatcher: Matcher<View>) {
    /**
     * Specify the Espresso matches which will satisfy the condition
     */
    fun toMatch(viewChecker: Matcher<View>) = waitForCondition(object : Instruction() {
        override fun getDescription(): String {
            val desc = StringDescription()
            desc.appendText("Wait for view ")
            viewMatcher.describeTo(desc)
            desc.appendText(" to match ")
            viewChecker.describeTo(desc)
            return desc.toString()
        }

        override fun checkCondition(): Boolean {
            return try {
                onView(viewMatcher).check(matches(viewChecker))
                true
            } catch (x: AssertionError) {
                false
            }
        }
    })
}

It also produces nice error messages on timeout:

java.lang.Exception: Wait for view with id: your.package.here.mock:id/searchfield_clearbutton to match (is displayed on the screen to the user and is enabled) - took more than 5 seconds. Test stopped.

This feels very natural to people familiar with Espresso testing and I think it would make a nice addition to your library. Your matchers can get as complex as Espresso allows without having to write custom Instruction classes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant