Skip to content

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

Description

@freakingawesome

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions