View Actions in Espresso

TheHumansAreDead-8” by Joe Van licensed under CC BY 2.0

The Espresso UI testing framework allows you use View Matchers and View Assertions to validate the behavior of your application running on an emulator or device. Using View Actions we can also simulate user behavior.

The ViewActions class provides the following actions for clicks and gestures:

  • click()
  • doubleClick()
  • longClick()
  • pressBack()
  • pressIMEActionButton()
  • pressKey(int)
  • pressMenuKey()
  • closeSoftKeyboard()
  • openLink()
  • scrollTo()
  • swipeLeft()
  • swipeRight()
  • swipeUp()
  • swipeDown()

In addition the following actions are available to directly manipulate text:

  • clearText()
  • typeText(String)
  • typeTextIntoFocusedView(String)
  • replaceText(String)

In the sample application built using the Basic Activity template in Android Studio there exists a FloatingActionButton. Tapping on this button displays a Snackbar with the text “Replace with your own action”.

Testing this behavior requires executing two view interactions. The first interaction will match the FloatingActionButton using its id and perform a click. The second will match the resulting Snackbar using the expected text then assert the text is displayed on the screen.

public void onFabClick_shouldDisplaySnackbar() throws Exception {
onView(withText("Replace with your own action"))

Using view actions we can simulate everything from simple clicks to complex navigation and user input.

UI testing with Espresso allows you to test complex flows in your application that otherwise may be difficult to unit test.

One final word of caution is that UI testing should not be a replacement for unit tests and should not be used for TDD. Unit tests and integration tests should still make up the bulk of your comprehensive automated test suite.

UI testing rather is a final layer of defense in the test pyramid that adds an additional safeguard against shipping defects in your code.

If you get a failure in a high level test, not just do you have a bug in your functional code, you also have a missing unit test. Thus whenever you fix a failing end-to-end test, you should be adding unit tests too.
— Martin Fowler