---
title: ViewMatchers, ViewActions and ViewAssertions | TestingBot
description: Every line of an Espresso test is built from three kinds of objects.
  A **ViewMatcher** describes which view you mean. A **ViewAction** does something
  to it.…
source_url:
  html: https://testingbot.com/resources/courses/espresso/matchers-actions-assertions
  md: https://testingbot.com/resources/courses/espresso/matchers-actions-assertions.md
---

Course

[Espresso Android Testing in Kotlin](https://testingbot.com/resources/courses/espresso)

Chapter 3 of 10

1. [1 Espresso Android Testing Tutorial in Kotlin](https://testingbot.com/resources/courses/espresso)
2. [2 Gradle Setup and Your First Espresso Run](https://testingbot.com/resources/courses/espresso/gradle-setup)
3. [3 ViewMatchers, ViewActions and ViewAssertions](https://testingbot.com/resources/courses/espresso/matchers-actions-assertions)
4. [4 Lists with RecyclerViewActions, and Espresso-Intents](https://testingbot.com/resources/courses/espresso/recyclerview-and-intents)
5. [5 Synchronisation and IdlingResources](https://testingbot.com/resources/courses/espresso/synchronisation-and-idling-resources)
6. [6 Test Isolation, Orchestrator and the Robot Pattern](https://testingbot.com/resources/courses/espresso/test-isolation-and-robots)
7. [7 Building the App APK and the Test APK](https://testingbot.com/resources/courses/espresso/build-the-apks)
8. [8 Run Espresso Tests on TestingBot](https://testingbot.com/resources/courses/espresso/run-on-testingbot)
9. [9 Running Espresso in CI with GitHub Actions](https://testingbot.com/resources/courses/espresso/ci-github-actions)
10. [10 Espresso Knowledge Check](https://testingbot.com/resources/courses/espresso/knowledge-check)

[Exit course](https://testingbot.com/resources/courses)

 Chapter 3 of 10 Intermediate 7 min read 2 quick checks Updated Nov 2026 

# ViewMatchers, ViewActions and ViewAssertions
On this page
1. [ViewMatchers: say which view you mean](https://testingbot.com#viewmatchers-say-which-view-you-mean)
2. [The two errors you will see most](https://testingbot.com#the-two-errors-you-will-see-most)
3. [ViewActions: do what the user does](https://testingbot.com#viewactions-do-what-the-user-does)
4. [ViewAssertions: check the result](https://testingbot.com#viewassertions-check-the-result)
5. [The login tests](https://testingbot.com#the-login-tests)

Every line of an Espresso test is built from three kinds of objects. A **ViewMatcher** describes which view you mean. A **ViewAction** does something to it. A **ViewAssertion** checks something about it. Once you know the handful that cover most tests, and the two errors Espresso throws when a matcher is wrong, you can test almost any screen built with Android views.

```kotlin
onView(withId(R.id.login)) // ViewMatcher: which view
    .perform(click()) // ViewAction: what to do
onView(withId(R.id.error))
    .check(matches(isDisplayed())) // ViewAssertion: what must be true
```

All three live in `espresso-core`. Their packages are `androidx.test.espresso.matcher.ViewMatchers`, `androidx.test.espresso.action.ViewActions` and `androidx.test.espresso.assertion.ViewAssertions`; Android Studio imports them for you.

## ViewMatchers: say which view you mean[#](https://testingbot.com#viewmatchers-say-which-view-you-mean)

`onView()` takes a Hamcrest matcher and searches the current window's view hierarchy for exactly one view that matches it. The matchers you will use most:

| Matcher | Matches | Use it when |
| --- | --- | --- |
| `withId(R.id.login)` | The view with that id | The view has an id. This is the default choice. |
| `withText("Log in")` | A `TextView` (or `Button`, `EditText`) with that text | There is no id, or the text is what you are testing |
| `withText(R.string.login_failed)` | Text from a string resource | You check copy that may change or be translated |
| `withHint("Password")` | An `EditText` with that hint | Empty fields without ids |
| `withContentDescription("Close")` | A view with that accessibility label | Icon buttons |
| `isDisplayed()` | A view that is at least partly on screen | Narrowing a matcher that would otherwise match hidden views |

Combine them with Hamcrest's `allOf` when one matcher is not specific enough:

```kotlin
onView(allOf(withId(R.id.add), hasSibling(withText("Product 3"))))
```

Prefer ids. Text changes when someone rewrites the copy or the device runs in another language; ids are part of the code and the compiler checks them. When you do match on copy, `withText(R.string.login_failed)` follows the string resource wherever it goes, including translations.

## The two errors you will see most[#](https://testingbot.com#the-two-errors-you-will-see-most)

A matcher must match **exactly one** view in the hierarchy. When it does not, Espresso throws one of two exceptions, and the message tells you which mistake you made. Both of these came from real runs against the sample app's product list:

```
androidx.test.espresso.AmbiguousViewMatcherException:
'an instance of android.widget.TextView and view.getText() with or without
transformation to match: is "Add"' matches 10 views in the hierarchy
```

Every row in the list has an "Add" button, so `withText("Add")` is ambiguous. (Ten, because only ten rows exist as views at that moment: a `RecyclerView` creates views for the visible rows only.) The fix is a more specific matcher, or, for lists, the `RecyclerViewActions` in the next chapter.

```
androidx.test.espresso.NoMatchingViewException: No views in hierarchy found
matching: an instance of android.widget.TextView and view.getText() with or
without transformation to match: is "Product 42"
```

"Product 42" exists in the adapter's data, but its row is far below the screen, so no view for it has been created yet. Espresso only sees views that exist. Under the message, both exceptions print the whole view hierarchy, which is the fastest way to see what Espresso actually found.

`onView(withText("Delete")).perform(click())` fails with AmbiguousViewMatcherException on a screen with a toolbar Delete action and a Delete button in a dialog. What do you change?

 Add `Thread.sleep` so the dialog has time to settle Match the button by its id, or combine `withText` with another matcher such as `withId` Catch the exception and click the first view

The error means more than one view matched; timing has nothing to do with it. A more specific matcher picks exactly one view. Espresso deliberately offers no "first match" fallback, because a test that clicks whichever view comes first breaks silently when the layout changes.

## ViewActions: do what the user does[#](https://testingbot.com#viewactions-do-what-the-user-does)

`perform()` takes one or more actions and runs them in order on the matched view:

| Action | What it does |
| --- | --- |
| `click()` | Taps the centre of the view |
| `typeText("alice")` | Focuses the field and types through the keyboard, character by character |
| `replaceText("alice")` | Sets the text directly, without the keyboard |
| `clearText()` | Empties a text field |
| `closeSoftKeyboard()` | Hides the on-screen keyboard |
| `pressImeActionButton()` | Presses the keyboard's action key (Done, Search, Next) |
| `scrollTo()` | Scrolls a `ScrollView` until the view is visible |
| `swipeLeft()`, `swipeUp()`, ... | Swipes on the view |

`typeText` behaves most like a user and triggers text watchers and input filters on each character. `replaceText` is faster and does not depend on the keyboard, which makes it the better choice when you only need the field filled in. Whichever you use, close the keyboard before tapping something below the fields: on a small screen the keyboard covers the Log in button, and Espresso refuses to click a view that is not displayed enough to receive the tap.

`scrollTo()` is meant for views inside a `ScrollView` (or `NestedScrollView`, `HorizontalScrollView`). It cannot bring an off-screen `RecyclerView` row into view: `onView(withText("Product 42")).perform(scrollTo())` fails with the same `NoMatchingViewException` as above, because the row's view does not exist yet for `onView` to find. Lists get their own actions in the next chapter.

## ViewAssertions: check the result[#](https://testingbot.com#viewassertions-check-the-result)

`check()` takes an assertion. Nearly every assertion you write is `matches(...)` with a view matcher inside:

```kotlin
onView(withId(R.id.error)).check(matches(withText(R.string.login_failed)))
onView(withId(R.id.progress)).check(matches(not(isDisplayed())))
onView(withId(R.id.welcome)).check(doesNotExist())
```

The difference between the last two matters. `matches(not(isDisplayed()))` needs the view to exist and be hidden; it throws `NoMatchingViewException` if the view is not in the hierarchy at all. `doesNotExist()` passes only when no view matches. Use the first for a spinner that is hidden, the second for a screen you have left.

`check()` returns the same `ViewInteraction`, so assertions chain:

```kotlin
onView(withId(R.id.error))
    .check(matches(isDisplayed()))
    .check(matches(withText(R.string.login_failed)))
```

## The login tests[#](https://testingbot.com#the-login-tests)

Put together, the first real tests for the login screen in `LoginTest.kt`:

```kotlin
@RunWith(AndroidJUnit4::class)
class LoginTest {

    @get:Rule
    val activityRule = ActivityScenarioRule(LoginActivity::class.java)

    @Test
    fun validLoginOpensProducts() {
        onView(withId(R.id.username)).perform(typeText("alice"))
        onView(withId(R.id.password)).perform(typeText("secret"), closeSoftKeyboard())
        onView(withId(R.id.login)).perform(click())

        onView(withId(R.id.welcome)).check(matches(withText("Welcome, alice")))
    }

    @Test
    fun wrongPasswordShowsError() {
        onView(withId(R.id.username)).perform(typeText("alice"))
        onView(withId(R.id.password)).perform(typeText("nope"), closeSoftKeyboard())
        onView(withId(R.id.login)).perform(click())

        onView(withId(R.id.error))
            .check(matches(isDisplayed()))
            .check(matches(withText(R.string.login_failed)))
    }
}
```

`R.id.welcome` lives on the next screen, `ProductsActivity`. Espresso does not care which activity a view belongs to: `onView` searches whatever window is in front.

Run them, and both fail:

```
Error in wrongPasswordShowsError(com.example.shop.LoginTest):
Expected: an instance of android.widget.TextView and view.getText() equals
string from resource id: <2131492900> [login_failed] value: Wrong username or password
     Got: view.getText() was ""

Error in validLoginOpensProducts(com.example.shop.LoginTest):
androidx.test.espresso.NoMatchingViewException: No views in hierarchy found
matching: view.getId() is <2131230910/com.example.shop:id/welcome>
```

The tests are right; the app checks the password on a background thread that takes 1.5 seconds, and Espresso checked the result immediately. This is the one situation where Espresso's automatic waiting needs help, and chapter 4 fixes it properly, without a sleep. Keep both tests as they are until then.

After logging out, you want to assert that the welcome text is gone because the products screen has closed. Which check is right?

 `check(matches(not(isDisplayed())))` `check(matches(withText("")))` `check(doesNotExist())`

Once the activity is finished, its views are no longer in the hierarchy. `matches(not(isDisplayed()))` would throw NoMatchingViewException because it needs a view to inspect; `doesNotExist()` is the assertion for "no such view".

[Previous · Chapter 2 Gradle Setup and Your First Espresso Run](https://testingbot.com/resources/courses/espresso/gradle-setup) [Next · Chapter 4 Lists with RecyclerViewActions, and Espresso-Intents](https://testingbot.com/resources/courses/espresso/recyclerview-and-intents)

On this page

1. [ViewMatchers: say which view you mean](https://testingbot.com#viewmatchers-say-which-view-you-mean)
2. [The two errors you will see most](https://testingbot.com#the-two-errors-you-will-see-most)
3. [ViewActions: do what the user does](https://testingbot.com#viewactions-do-what-the-user-does)
4. [ViewAssertions: check the result](https://testingbot.com#viewassertions-check-the-result)
5. [The login tests](https://testingbot.com#the-login-tests)

Certification

Earn the free, resume-worthy TestingBot Espresso Certification for this course.

[How it works](https://testingbot.com/resources/courses/espresso/certification)
