Testing user interactions within a single app helps to ensure that users do not encounter unexpected results or have a poor experience when interacting with your app. You should get into the habit of creating user interface (UI) tests if you need to verify that the UI of your app is functioning correctly.
The Espresso testing framework, provided by
AndroidX Test,
provides APIs for writing UI tests to simulate
user interactions within a
single target app. Espresso tests can run on
devices running Android 4.0.1 (API level 14) and
higher. A key benefit of using Espresso is
that it provides automatic synchronization of test
actions with the UI of the app you are testing.
Espresso detects when the main thread is idle,
so it is able to run your test commands
at the appropriate time, improving the reliability of
your tests. This capability also relieves you
from having to add any timing workarounds,
such as Thread.sleep()
in your test code.
The Espresso testing framework is
an instrumentation-based API and works with the
AndroidJUnitRunner
test runner.
Set up Espresso
Before building your UI test with Espresso, make sure to set a dependency reference to the Espresso library:
dependencies { androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0' }
Turn off animations on your test device — leaving system animations turned on in the test device might cause unexpected results or may lead your test to fail. Turn off animations from Settings by opening Developer options and turning all the following options off:
- Window animation scale
- Transition animation scale
- Animator duration scale
If you want to set up your project to use Espresso features other than what the core API provides, see the guides specific to Espresso.
Create an Espresso test class
To create an Espresso test, follow this programming model:
-
Find the UI component you want to test in
an
Activity
(for example, a sign-in button in the app) by calling theonView()
method, or theonData()
method forAdapterView
controls. -
Simulate a specific user interaction to
perform on that UI component, by calling the
ViewInteraction.perform()
orDataInteraction.perform()
method and passing in the user action (for example, click on the sign-in button). To sequence multiple actions on the same UI component, chain them using a comma-separated list in your method argument. - Repeat the steps above as necessary, to simulate a user flow across multiple activities in the target app.
-
Use the
ViewAssertions
methods to check that the UI reflects the expected state or behavior, after these user interactions are performed.
These steps are covered in more detail in the sections below.
The following code snippet shows how your test class might invoke this basic workflow:
Kotlin
onView(withId(R.id.my_view)) // withId(R.id.my_view) is a ViewMatcher .perform(click()) // click() is a ViewAction .check(matches(isDisplayed())) // matches(isDisplayed()) is a ViewAssertion
Java
onView(withId(R.id.my_view)) // withId(R.id.my_view) is a ViewMatcher .perform(click()) // click() is a ViewAction .check(matches(isDisplayed())); // matches(isDisplayed()) is a ViewAssertion
Use Espresso with ActivityScenarioRule
The following section describes how to create a
new Espresso test in the JUnit 4 style and use
ActivityScenarioRule
to reduce the amount of boilerplate code you need to write. By using
ActivityScenarioRule
,
the testing framework launches the activity under test
before each test method annotated with
@Test
and before any method annotated with
@Before
. The framework handles
shutting down the activity after the test finishes
and all methods annotated with @After
are run.
Kotlin
package com.example.android.testing.espresso.BasicSample import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import androidx.test.ext.junit.rules.ActivityScenarioRule import androidx.test.ext.junit.runners.AndroidJUnit4 @RunWith(AndroidJUnit4::class) @LargeTest class ChangeTextBehaviorTest { private lateinit var stringToBetyped: String @get:Rule var activityRule: ActivityScenarioRule<MainActivity> = ActivityScenarioRule(MainActivity::class.java) @Before fun initValidString() { // Specify a valid string. stringToBetyped = "Espresso" } @Test fun changeText_sameActivity() { // Type text and then press the button. onView(withId(R.id.editTextUserInput)) .perform(typeText(stringToBetyped), closeSoftKeyboard()) onView(withId(R.id.changeTextBt)).perform(click()) // Check that the text was changed. onView(withId(R.id.textToBeChanged)) .check(matches(withText(stringToBetyped))) } }
Java
package com.example.android.testing.espresso.BasicSample; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import androidx.test.ext.junit.rules.ActivityScenarioRule; import androidx.test.ext.junit.runners.AndroidJUnit4; @RunWith(AndroidJUnit4.class) @LargeTest public class ChangeTextBehaviorTest { private String stringToBetyped; @Rule public ActivityScenarioRule<MainActivity> activityRule = new ActivityScenarioRule<>(MainActivity.class); @Before public void initValidString() { // Specify a valid string. stringToBetyped = "Espresso"; } @Test public void changeText_sameActivity() { // Type text and then press the button. onView(withId(R.id.editTextUserInput)) .perform(typeText(stringToBetyped), closeSoftKeyboard()); onView(withId(R.id.changeTextBt)).perform(click()); // Check that the text was changed. onView(withId(R.id.textToBeChanged)) .check(matches(withText(stringToBetyped))); } }
Access UI components
Before Espresso can interact with the app under test, you must first specify the UI component or view. Espresso supports the use of Hamcrest matchers for specifying views and adapters in your app.
To find the view, call the
onView()
method and pass in a view matcher that
specifies the view that you are targeting. This is
described in more detail in
Specify a view matcher.
The onView()
method returns a
ViewInteraction
object that allows your test to interact with the view.
However, calling the
onView()
method may not work if you want to locate a view in
an RecyclerView
layout.
In this case, follow the instructions in
Locating a view in an AdapterView
instead.
Note:
The onView()
method does not check if the view you specified is
valid. Instead, Espresso searches only the
current view hierarchy, using the matcher provided.
If no match is found, the method throws a
NoMatchingViewException
.
The following code snippet shows how you might write a test that accesses an
EditText
field,
enters a string of text, closes the virtual keyboard,
and then performs a button click.
Kotlin
fun testChangeText_sameActivity() { // Type text and then press the button. onView(withId(R.id.editTextUserInput)) .perform(typeText(STRING_TO_BE_TYPED), closeSoftKeyboard()) onView(withId(R.id.changeTextButton)).perform(click()) // Check that the text was changed. ... }
Java
public void testChangeText_sameActivity() { // Type text and then press the button. onView(withId(R.id.editTextUserInput)) .perform(typeText(STRING_TO_BE_TYPED), closeSoftKeyboard()); onView(withId(R.id.changeTextButton)).perform(click()); // Check that the text was changed. ... }
Specify a view matcher
You can specify a view matcher by using these approaches:
- Calling methods in the
ViewMatchers
class. For example, to find a view by looking for a text string it displays, you can call a method like this:Kotlin
onView(withText("Sign-in"))
Java
onView(withText("Sign-in"));
Similarly you can call
withId()
and providing the resource ID (R.id
) of the view, as shown in the following example:Kotlin
onView(withId(R.id.button_signin))
Java
onView(withId(R.id.button_signin));
Android resource IDs are not guaranteed to be unique. If your test attempts to match to a resource ID used by more than one view, Espresso throws an
AmbiguousViewMatcherException
. -
Using the Hamcrest
Matchers
class. You can use theallOf()
methods to combine multiple matchers, such ascontainsString()
andinstanceOf()
. This approach allows you to filter the match results more narrowly, as shown in the following example:Kotlin
onView(allOf(withId(R.id.button_signin), withText("Sign-in")))
Java
onView(allOf(withId(R.id.button_signin), withText("Sign-in")));
You can use the
not
keyword to filter for views that don't correspond to the matcher, as shown in the following example:Kotlin
onView(allOf(withId(R.id.button_signin), not(withText("Sign-out"))))
Java
onView(allOf(withId(R.id.button_signin), not(withText("Sign-out"))));
To use these methods in your test, import the
org.hamcrest.Matchers
package. To learn more about Hamcrest matching, see the Hamcrest site.
To improve the performance of your Espresso tests,
specify the minimum matching information
needed to find your target view. For example,
if a view is uniquely identifiable by its
descriptive text, you do not need to specify
that it is also assignable from the
TextView
instance.
Locate a view in an AdapterView
In an AdapterView
widget,
the view is dynamically populated with child
views at runtime. If the target view you want to test is inside an
AdapterView
(such as a ListView
,
GridView
, or
Spinner
), the
onView()
method might not work because only a
subset of the views may be loaded in the current view hierarchy.
Instead, call the
onData()
method to obtain a
DataInteraction
object to access the target view element.
Espresso handles loading the target view element
into the current view hierarchy. Espresso
also takes care of scrolling to the target element,
and putting the element into focus.
Note: The
onData()
method does not check if the item you
specified corresponds with a view. Espresso searches
only the current view hierarchy. If no match is found, the method throws a
NoMatchingViewException
.
The following code snippet shows how you can use the
onData()
method together
with Hamcrest matching to search for a specific
row in a list that contains a given string.
In this example, the LongListActivity
class
contains a list of strings exposed
through a SimpleAdapter
.
Kotlin
onData(allOf(`is`(instanceOf(Map::class.java)), hasEntry(equalTo(LongListActivity.ROW_TEXT), `is`("test input"))))
Java
onData(allOf(is(instanceOf(Map.class)), hasEntry(equalTo(LongListActivity.ROW_TEXT), is("test input"))));
Perform actions
Call the
ViewInteraction.perform()
or
DataInteraction.perform()
methods to
simulate user interactions on the UI component. You must pass in one or more
ViewAction
objects as arguments. Espresso fires each action in sequence according to
the given order, and executes them in the main thread.
The
ViewActions
class provides a list of helper methods for specifying common actions.
You can use these methods as convenient shortcuts
instead of creating and configuring individual
ViewAction
objects. You can specify such actions as:
-
ViewActions.click()
: Clicks on the view. -
ViewActions.typeText()
: Clicks on a view and enters a specified string. -
ViewActions.scrollTo()
: Scrolls to the view. The target view must be subclassed fromScrollView
and the value of itsandroid:visibility
property must beVISIBLE
. For views that extendAdapterView
(for example,ListView
), theonData()
method takes care of scrolling for you. -
ViewActions.pressKey()
: Performs a key press using a specified keycode. -
ViewActions.clearText()
: Clears the text in the target view.
If the target view is inside a ScrollView
,
perform the
ViewActions.scrollTo()
action first to display the view in the screen before other proceeding
with other actions. The
ViewActions.scrollTo()
action will have no effect if the view is already displayed.
Test your activities in isolation with Espresso Intents
Espresso Intents enables validation and stubbing of intents sent out by an app. With Espresso Intents, you can test an app, activity, or service in isolation by intercepting outgoing intents, stubbing the result, and sending it back to the component under test.
To begin testing with Espresso Intents, you need to add the following line to your app's build.gradle file:
dependencies { androidTestImplementation 'androidx.test.espresso:espresso-intents:3.1.0' }
To use Espresso Intents, you first need to initialize it in the test setup via
Intents.init()a>
You may also want to use
ActivityScenarioRule
to launch the host activity before each test.
The test class shown in the following codes snippet provides a simple test for an explicit intent. It tests the activities and intents created in the Building Your First App tutorial.
Kotlin
private const val MESSAGE = "This is a test" private const val PACKAGE_NAME = "com.example.myfirstapp" @RunWith(AndroidJUnit4::class) class SimpleIntentTest { /* Instantiate an ActivityScenarioRule object. */ @get:Rule var activityRule: ActivityScenarioRule<MainActivity> = ActivityScenarioRule(MainActivity::class.java) @Before fun setUp() { Intents.init() } @After fun tearDown() { Intents.release() } @Test fun verifyMessageSentToMessageActivity() { // Types a message into a EditText element. onView(withId(R.id.edit_message)) .perform(typeText(MESSAGE), closeSoftKeyboard()) // Clicks a button to send the message to another // activity through an explicit intent. onView(withId(R.id.send_message)).perform(click()) // Verifies that the DisplayMessageActivity received an intent // with the correct package name and message. intended(allOf( hasComponent(hasShortClassName(".DisplayMessageActivity")), toPackage(PACKAGE_NAME), hasExtra(MainActivity.EXTRA_MESSAGE, MESSAGE))) } }
Java
@Large @RunWith(AndroidJUnit4.class) public class SimpleIntentTest { private static final String MESSAGE = "This is a test"; private static final String PACKAGE_NAME = "com.example.myfirstapp"; /* Instantiate an ActivityScenarioRule object. */ @Rule public ActivityScenarioRule<MainActivity> activityRule = new ActivityScenarioRule<>(MainActivity.class); @Before public void setUp() { Intents.init() } @After public void tearDown() { Intents.release() } @Test public void verifyMessageSentToMessageActivity() { // Types a message into a EditText element. onView(withId(R.id.edit_message)) .perform(typeText(MESSAGE), closeSoftKeyboard()); // Clicks a button to send the message to another // activity through an explicit intent. onView(withId(R.id.send_message)).perform(click()); // Verifies that the DisplayMessageActivity received an intent // with the correct package name and message. intended(allOf( hasComponent(hasShortClassName(".DisplayMessageActivity")), toPackage(PACKAGE_NAME), hasExtra(MainActivity.EXTRA_MESSAGE, MESSAGE))); } }
For more information about Espresso Intents, see the Espresso Intents documentation on the AndroidX Test site. You can also download the IntentsBasicSample and IntentsAdvancedSample code samples.
Test WebViews with Espresso Web
Espresso Web allows you to test WebView
components
contained within an activity. It uses the
WebDriver API to inspect and control the
behavior of a WebView
.
To begin testing with Espresso Web, you need to add the following line to your app's build.gradle file:
dependencies { androidTestImplementation 'androidx.test.espresso:espresso-web:3.1.0' }
When creating a test using Espresso Web, you need to enable
JavaScript on the WebView
when you instantiate the
ActivityScenario
object to test the activity. In the tests, you can select
HTML elements displayed in the
WebView
and simulate user interactions, like
entering text into a text box and then clicking a button. After the actions
are completed, you can then verify that the results on the
Web page match the results that you expect.
In the following code snippet, the class tests
a WebView
component with the id value 'webview'
in the activity being tested.
The typeTextInInput_clickButton_SubmitsForm()
test selects an
<input>
element on the
Web page, enters some text, and checks text that appears in
another element.
Kotlin
private const val MACCHIATO = "Macchiato" private const val DOPPIO = "Doppio" @LargeTest @RunWith(AndroidJUnit4::class) class WebViewActivityTest { @Test fun typeTextInInput_clickButton_SubmitsForm() { // Lazily launch the Activity with a custom start Intent per test try (ActivityScenario.launch(withWebFormIntent())) { onWebView().forceJavascriptEnabled() // Selects the WebView in your layout. // If you have multiple WebViews you can also use a // matcher to select a given WebView, onWebView(withId(R.id.web_view)). onWebView() // Find the input element by ID .withElement(findElement(Locator.ID, "text_input")) // Clear previous input .perform(clearElement()) // Enter text into the input element .perform(DriverAtoms.webKeys(MACCHIATO)) // Find the submit button .withElement(findElement(Locator.ID, "submitBtn")) // Simulate a click via JavaScript .perform(webClick()) // Find the response element by ID .withElement(findElement(Locator.ID, "response")) // Verify that the response page contains the entered text .check(webMatches(getText(), containsString(MACCHIATO))) } } }
Java
@LargeTest @RunWith(AndroidJUnit4.class) public class WebViewActivityTest { private static final String MACCHIATO = "Macchiato"; private static final String DOPPIO = "Doppio"; @Test public void typeTextInInput_clickButton_SubmitsForm() { // Lazily launch the Activity with a custom start Intent per test try (ActivityScenario.launch(withWebFormIntent())) { // Enable JavaScript. onWebView().forceJavascriptEnabled(); // Selects the WebView in your layout. // If you have multiple WebViews you can also use a // matcher to select a given WebView, onWebView(withId(R.id.web_view)). onWebView() // Find the input element by ID .withElement(findElement(Locator.ID, "text_input")) // Clear previous input .perform(clearElement()) // Enter text into the input element .perform(DriverAtoms.webKeys(MACCHIATO)) // Find the submit button .withElement(findElement(Locator.ID, "submitBtn")) // Simulate a click via JavaScript .perform(webClick()) // Find the response element by ID .withElement(findElement(Locator.ID, "response")) // Verify that the response page contains the entered text .check(webMatches(getText(), containsString(MACCHIATO))); } } }
For more information about Espresso Web, see the Espresso Web documentation on the AndroidX Test site.. You can also download this code snippet as part of the Espresso Web code sample.
Verify results
Call the
ViewInteraction.check()
or
DataInteraction.check()
method to assert
that the view in the UI matches some expected state. You must pass in a
ViewAssertion
object as the argument. If the assertion fails, Espresso throws
an AssertionFailedError
.
The
ViewAssertions
class provides a list of helper methods for specifying common
assertions. The assertions you can use include:
-
doesNotExist
: Asserts that there is no view matching the specified criteria in the current view hierarchy. -
matches
: Asserts that the specified view exists in the current view hierarchy and its state matches some given Hamcrest matcher. -
selectedDescendentsMatch
: Asserts that the specified children views for a parent view exist, and their state matches some given Hamcrest matcher.
The following code snippet shows how you might
check that the text displayed in the UI has
the same value as the text previously entered in the
EditText
field.
Kotlin
fun testChangeText_sameActivity() { // Type text and then press the button. ... // Check that the text was changed. onView(withId(R.id.textToBeChanged)) .check(matches(withText(STRING_TO_BE_TYPED))) }
Java
public void testChangeText_sameActivity() { // Type text and then press the button. ... // Check that the text was changed. onView(withId(R.id.textToBeChanged)) .check(matches(withText(STRING_TO_BE_TYPED))); }
Run Espresso tests on a device or emulator
You can run Espresso tests from
Android Studio or
from the command-line. Make sure to specify
AndroidJUnitRunner
as the default instrumentation runner in your project.
To run your Espresso test, follow the steps for running instrumented tests described in Getting Started with Testing.
You should also read Espresso API Reference.
Additional resources
For more information about using UI Automator in Android tests, consult the following resources.
Samples
- Espresso Code Samples includes a full selection of Espresso samples.