docs: Adding Espresso Intent and Web docs

Bug: 20721203
Bug: 20720633
bug: 27453733
Change-Id: I67a7d09a6652e3463728691f2a1f5679e900e776
This commit is contained in:
Eric Schmidt
2016-09-14 18:18:50 -07:00
parent a3252f103d
commit 34fb906c1a

View File

@@ -24,17 +24,11 @@ trainingnavtop=true
</h2> </h2>
<ol> <ol>
<li> <li><a href="#setup">Set Up Espresso</a></li>
<a href="#setup">Set Up Espresso</a>
</li>
<li> <li><a href="#build">Create an Espresso Test Class</a></li>
<a href="#build">Create an Espresso Test Class</a>
</li>
<li> <li><a href="#run">Run Espresso Tests on a Device or Emulator</a></li>
<a href="#run">Run Espresso Tests on a Device or Emulator</a>
</li>
</ol> </ol>
<h2> <h2>
@@ -64,26 +58,35 @@ trainingnavtop=true
<p> <p>
Testing user interactions Testing user interactions
within a single app helps to ensure that users do not within a single app helps to ensure that users do not
encounter unexpected results or have a poor experience when interacting with your app. encounter unexpected results or have a poor
You should get into the habit of creating user interface (UI) tests if you need to verify 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. that the UI of your app is functioning correctly.
</p> </p>
<p> <p>
The Espresso testing framework, provided by the The Espresso testing framework, provided by the
<a href="{@docRoot}tools/testing-support-library/index.html">Android Testing Support Library</a>, <a href="{@docRoot}tools/testing-support-library/index.html">Android Testing Support Library</a>,
provides APIs for writing UI tests to simulate user interactions within a provides APIs for writing UI tests to simulate
single target app. Espresso tests can run on devices running Android 2.2 (API level 8) and user interactions within a
higher. A key benefit of using Espresso is that it provides automatic synchronization of test single target app. Espresso tests can run on
actions with the UI of the app you are testing. Espresso detects when the main thread is idle, devices running Android 2.3.3 (API level 10) and
so it is able to run your test commands at the appropriate time, improving the reliability of higher. A key benefit of using Espresso is
your tests. This capability also relieves you from having to adding any timing workarounds, that it provides automatic synchronization of test
such as a sleep period, in your test code. 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 {@link java.lang.Thread#sleep(long) Thread.sleep()}
in your test code.
</p> </p>
<p> <p>
The Espresso testing framework is an instrumentation-based API and works The Espresso testing framework is
with the an instrumentation-based API and works with the
<a href="{@docRoot}reference/android/support/test/runner/AndroidJUnitRunner.html">{@code <a href="{@docRoot}reference/android/support/test/runner/AndroidJUnitRunner.html">{@code
AndroidJUnitRunner}</a> test runner. AndroidJUnitRunner}</a> test runner.
</p> </p>
@@ -92,25 +95,36 @@ trainingnavtop=true
Set Up Espresso Set Up Espresso
</h2> </h2>
<p>Before building your UI test with Espresso, make sure to configure your test source code <p>
Before building your UI test with Espresso,
make sure to configure your test source code
location and project dependencies, as described in location and project dependencies, as described in
<a href="{@docRoot}training/testing/start/index.html#config-instrumented-tests"> <a href="{@docRoot}training/testing/start/index.html#config-instrumented-tests">Getting Started with Testing</a>.
Getting Started with Testing</a>.</p> </p>
<p>In the {@code build.gradle} file of your Android app module, you must set a dependency <p>
reference to the Espresso library:</p> In the {@code build.gradle} file of your Android app
module, you must set a dependency
reference to the Espresso library:
</p>
<pre> <pre>
dependencies { dependencies {
... // Other dependencies ...
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1' androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
} }
</pre> </pre>
<p>Turn off animations on your test device &mdash; leaving system animations turned on in the test <p>
device might cause unexpected results or may lead your test to fail. Turn off animations from Turn off animations on your test device &mdash;
<em>Settings</em> by opening <em>Developing Options</em> and turning all the following options off: leaving system animations turned on in the test
device might cause unexpected results or may
lead your test to fail. Turn off animations from
<em>Settings</em> by opening <em>Developer options</em>
and turning all the following options off:
</p> </p>
<p>
<ul> <ul>
<li> <li>
<strong>Window animation scale</strong> <strong>Window animation scale</strong>
@@ -124,23 +138,30 @@ device might cause unexpected results or may lead your test to fail. Turn off an
<strong>Animator duration scale</strong> <strong>Animator duration scale</strong>
</li> </li>
</ul> </ul>
</li> </p>
</ul>
<p>If you want to set up your project to use Espresso features other than what the core API <p>
If you want to set up your project to use Espresso
features other than what the core API
provides, see this provides, see this
<a href="https://google.github.io/android-testing-support-library/docs/espresso/index.html" <a href="https://google.github.io/android-testing-support-library/docs/espresso/index.html"
class="external-link">resource</a>.</p> class="external-link">resource</a>.</p>
<!-- Section 2 -->
<h2 id="build"> <h2 id="build">
Create an Espresso Test Class Create an Espresso Test Class
</h2> </h2>
<p> <p>
To create an Espresso test, create a Java class that follows this programming model: To create an Espresso test, create a Java
class that follows this programming model:
</p> </p>
<ol> <ol>
<li>Find the UI component you want to test in an {@link android.app.Activity} (for example, a <li>
Find the UI component you want to test in
an {@link android.app.Activity} (for example, a
sign-in button in the app) by calling the sign-in button in the app) by calling the
<a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onView(org.hamcrest.Matcher<android.view.View>)"> <a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onView(org.hamcrest.Matcher<android.view.View>)">
{@code onView()}</a> method, or the {@code onView()}</a> method, or the
@@ -148,20 +169,25 @@ device might cause unexpected results or may lead your test to fail. Turn off an
{@code onData()}</a> method for {@link android.widget.AdapterView} controls. {@code onData()}</a> method for {@link android.widget.AdapterView} controls.
</li> </li>
<li>Simulate a specific user interaction to perform on that UI component, by calling the <li>
Simulate a specific user interaction to
perform on that UI component, by calling the
<a href="{@docRoot}reference/android/support/test/espresso/ViewInteraction.html#perform(android.support.test.espresso.ViewAction...)">{@code ViewInteraction.perform()}</a> <a href="{@docRoot}reference/android/support/test/espresso/ViewInteraction.html#perform(android.support.test.espresso.ViewAction...)">{@code ViewInteraction.perform()}</a>
or or
<a href="{@docRoot}reference/android/support/test/espresso/DataInteraction.html#perform(android.support.test.espresso.ViewAction...)">{@code DataInteraction.perform()}</a> <a href="{@docRoot}reference/android/support/test/espresso/DataInteraction.html#perform(android.support.test.espresso.ViewAction...)">{@code DataInteraction.perform()}</a>
method and passing in the user action (for example, click on the sign-in button). To sequence 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 multiple actions on the same UI component, chain them using a comma-separated list in your
method argument. method argument.
</li> </li>
<li>Repeat the steps above as necessary, to simulate a user flow across multiple <li>
Repeat the steps above as necessary, to simulate a user flow across multiple
activities in the target app. activities in the target app.
</li> </li>
<li>Use the <li>
Use the
<a href="{@docRoot}reference/android/support/test/espresso/assertion/ViewAssertions.html">{@code ViewAssertions}</a> <a href="{@docRoot}reference/android/support/test/espresso/assertion/ViewAssertions.html">{@code ViewAssertions}</a>
methods to check that the UI reflects the expected methods to check that the UI reflects the expected
state or behavior, after these user interactions are performed. state or behavior, after these user interactions are performed.
@@ -173,7 +199,8 @@ device might cause unexpected results or may lead your test to fail. Turn off an
</p> </p>
<p> <p>
The following code snippet shows how your test class might invoke this basic workflow: The following code snippet shows how your test
class might invoke this basic workflow:
</p> </p>
<pre> <pre>
@@ -181,16 +208,26 @@ onView(withId(R.id.my_view)) // withId(R.id.my_view) is a ViewMatcher
.perform(click()) // click() is a ViewAction .perform(click()) // click() is a ViewAction
.check(matches(isDisplayed())); // matches(isDisplayed()) is a ViewAssertion .check(matches(isDisplayed())); // matches(isDisplayed()) is a ViewAssertion
</pre> </pre>
<h3 id="espresso-atr">Using Espresso with ActivityTestRule</h3>
<!-- Section 2.1 -->
<h3 id="espresso-atr">
Using Espresso with ActivityTestRule
</h3>
<p> <p>
The following section describes how to create a new Espresso test in the JUnit 4 style and use The following section describes how to create a
<a href="{@docRoot}reference/android/support/test/rule/ActivityTestRule.html"> new Espresso test in the JUnit 4 style and use
{@code ActivityTestRule}</a> to reduce the amount of boilerplate code you need to write. By using <a href="{@docRoot}reference/android/support/test/rule/ActivityTestRule.html">{@code ActivityTestRule}</a>
<a href="{@docRoot}reference/android/support/test/rule/ActivityTestRule.html"> to reduce the amount of boilerplate code you need to write. By using
{@code ActivityTestRule}</a>, the testing framework launches the activity under test <a href="{@docRoot}reference/android/support/test/rule/ActivityTestRule.html">{@code ActivityTestRule}</a>,
before each test method annotated with <code>&#64;Test</code> and before any method annotated with the testing framework launches the activity under test
<code>&#64;Before</code>. The framework handles shutting down the activity after the test finishes before each test method annotated with
and all methods annotated with <code>&#64;After</code> are run.</p> <code>&#64;Test</code> and before any method annotated with
<code>&#64;Before</code>. The framework handles
shutting down the activity after the test finishes
and all methods annotated with <code>&#64;After</code> are run.
</p>
<pre> <pre>
package com.example.android.testing.espresso.BasicSample; package com.example.android.testing.espresso.BasicSample;
@@ -234,101 +271,55 @@ public class ChangeTextBehaviorTest {
} }
</pre> </pre>
<h3 id="espresso-aitc2"> <!-- Section 2.2 -->
Using Espresso with ActivityInstrumentationTestCase2
</h3>
<p>The following section describes how to migrate to Espresso if you have existing test classes
subclassed from {@link android.test.ActivityInstrumentationTestCase2} and you don't want to rewrite
them to use JUnit4.</p>
<p class="note"><strong>Note:</strong> For new UI tests, we strongly recommend that you write your
test in the JUnit 4 style and use the
<a href="{@docRoot}reference/android/support/test/rule/ActivityTestRule.html">
{@code ActivityTestRule}</a> class, instead of
{@link android.test.ActivityInstrumentationTestCase2}.</p>
<p>
If you are subclassing {@link android.test.ActivityInstrumentationTestCase2}
to create your Espresso test class, you must inject an
{@link android.app.Instrumentation} instance into your test class. This step is required in
order for your Espresso test to run with the
<a href="{@docRoot}reference/android/support/test/runner/AndroidJUnitRunner.html">{@code AndroidJUnitRunner}</a>
test runner.
</p>
<p>
To do this, call the
{@link android.test.InstrumentationTestCase#injectInstrumentation(android.app.Instrumentation) injectInstrumentation()}
method and pass in the result of
<a href="{@docRoot}reference/android/support/test/InstrumentationRegistry.html#getInstrumentation()">
{@code InstrumentationRegistry.getInstrumentation()}</a>, as shown in the following code
example:
</p>
<pre>
import android.support.test.InstrumentationRegistry;
public class MyEspressoTest
extends ActivityInstrumentationTestCase2&lt;MyActivity&gt; {
private MyActivity mActivity;
public MyEspressoTest() {
super(MyActivity.class);
}
&#64;Before
public void setUp() throws Exception {
super.setUp();
injectInstrumentation(InstrumentationRegistry.getInstrumentation());
mActivity = getActivity();
}
...
}
</pre>
<p class="note"><strong>Note:</strong> Previously, {@link android.test.InstrumentationTestRunner}
would inject the {@link android.app.Instrumentation} instance, but this test runner is being
deprecated.</p>
<h3 id="accessing-ui-components"> <h3 id="accessing-ui-components">
Accessing UI Components Accessing UI Components
</h3> </h3>
<p> <p>
Before Espresso can interact with the app under test, you must first specify the UI component Before Espresso can interact with the app
under test, you must first specify the UI component
or <em>view</em>. Espresso supports the use of or <em>view</em>. Espresso supports the use of
<a href="http://hamcrest.org/" class="external-link">Hamcrest matchers</a> <a href="http://hamcrest.org/" class="external-link">Hamcrest matchers</a>
for specifying views and adapters in your app. for specifying views and adapters in your app.
</p> </p>
<p> <p>
To find the view, call the <a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onView(org.hamcrest.Matcher<android.view.View>)"> To find the view, call the
{@code onView()}</a> <a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onView(org.hamcrest.Matcher<android.view.View>)">{@code onView()}</a>
method and pass in a view matcher that specifies the view that you are targeting. This is method and pass in a view matcher that
described in more detail in <a href="#specifying-view-matcher">Specifying a View Matcher</a>. specifies the view that you are targeting. This is
The <a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onView(org.hamcrest.Matcher<android.view.View>)"> described in more detail in
{@code onView()}</a> method returns a <a href="#specifying-view-matcher">Specifying a View Matcher</a>.
<a href="{@docRoot}reference/android/support/test/espresso/ViewInteraction.html"> The <a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onView(org.hamcrest.Matcher<android.view.View>)">{@code onView()}</a>
{@code ViewInteraction}</a> method returns a
<a href="{@docRoot}reference/android/support/test/espresso/ViewInteraction.html">{@code ViewInteraction}</a>
object that allows your test to interact with the view. object that allows your test to interact with the view.
However, calling the <a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onView(org.hamcrest.Matcher<android.view.View>)"> However, calling the
{@code onView()}</a> method may not work if you want to locate a view in <a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onView(org.hamcrest.Matcher<android.view.View>)">
an {@link android.widget.AdapterView} layout. In this case, follow the instructions in {@code onView()}</a>
<a href="#locating-adpeterview-view">Locating a view in an AdapterView</a> instead. method may not work if you want to locate a view in
an {@link android.support.v7.widget.RecyclerView} layout.
In this case, follow the instructions in
<a href="#locating-adpeterview-view">Locating a view in an AdapterView</a>
instead.
</p> </p>
<p class="note"> <p class="note">
<strong>Note</strong>: The <a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onView(org.hamcrest.Matcher<android.view.View>)"> <strong>Note</strong>:
{@code onView()}</a> method does not check if the view you specified is The <a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onView(org.hamcrest.Matcher<android.view.View>)">{@code onView()}</a>
valid. Instead, Espresso searches only the current view hierarchy, using the matcher provided. 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 If no match is found, the method throws a
<a href="{@docRoot}reference/android/support/test/espresso/NoMatchingViewException.html"> <a href="{@docRoot}reference/android/support/test/espresso/NoMatchingViewException.html">{@code NoMatchingViewException}</a>.
{@code NoMatchingViewException}</a>.
</p> </p>
<p> <p>
The following code snippet shows how you might write a test that accesses an The following code snippet shows how you might write a test that accesses an
{@link android.widget.EditText} field, enters a string of text, closes the virtual keyboard, {@link android.widget.EditText} field,
enters a string of text, closes the virtual keyboard,
and then performs a button click. and then performs a button click.
</p> </p>
@@ -344,6 +335,7 @@ public void testChangeText_sameActivity() {
} }
</pre> </pre>
<!-- Section 2.2.1 -->
<h4 id="specifying-view-matcher"> <h4 id="specifying-view-matcher">
Specifying a View Matcher Specifying a View Matcher
</h4> </h4>
@@ -354,44 +346,59 @@ public void testChangeText_sameActivity() {
<ul> <ul>
<li>Calling methods in the <li>Calling methods in the
<a href="{@docRoot}reference/android/support/test/espresso/matcher/ViewMatchers.html"> <a href="{@docRoot}reference/android/support/test/espresso/matcher/ViewMatchers.html">{@code ViewMatchers}</a>
{@code ViewMatchers}</a> class. For example, to find a view by looking for a text string it class. For example, to find a view by looking for a text string it
displays, you can call a method like this: displays, you can call a method like this:
<pre> <pre>
onView(withText("Sign-in")); onView(withText("Sign-in"));
</pre> </pre>
<p>Similarly you can call <p>
<a href="{@docRoot}reference/android/support/test/espresso/matcher/ViewMatchers.html#withId(int)"> Similarly you can call
{@code withId()}</a> and providing the resource ID ({@code R.id}) of the view, as shown in the <a href="{@docRoot}reference/android/support/test/espresso/matcher/ViewMatchers.html#withId(int)">{@code withId()}</a>
following example:</p> and providing the resource ID ({@code R.id}) of the view,
as shown in the
following example:
</p>
<pre> <pre>
onView(withId(R.id.button_signin)); onView(withId(R.id.button_signin));
</pre> </pre>
<p> <p>
Android resource IDs are not guaranteed to be unique. If your test attempts to match to a 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 resource ID used by more than one view, Espresso throws an
<a href="{@docRoot}reference/android/support/test/espresso/AmbiguousViewMatcherException.html"> <a href="{@docRoot}reference/android/support/test/espresso/AmbiguousViewMatcherException.html">{@code AmbiguousViewMatcherException}</a>.
{@code AmbiguousViewMatcherException}</a>.
</p> </p>
</li> </li>
<li>Using the Hamcrest
<li>
Using the Hamcrest
<a href="http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html" <a href="http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html"
class="external-link">{@code Matchers}</a> class. You can use the class="external-link">{@code Matchers}</a> class. You can use the
{@code allOf()} methods to combine multiple matchers, such as {@code allOf()} methods to combine multiple matchers, such as
{@code containsString()} and {@code instanceOf()}. This approach allows you to {@code containsString()} and {@code instanceOf()}.
This approach allows you to
filter the match results more narrowly, as shown in the following example: filter the match results more narrowly, as shown in the following example:
<pre> <pre>
onView(allOf(withId(R.id.button_signin), withText("Sign-in"))); onView(allOf(withId(R.id.button_signin), withText("Sign-in")));
</pre> </pre>
<p>You can use the {@code not} keyword to filter for views that don't correspond to the matcher, as
shown in the following example:</p> <p>
You can use the {@code not} keyword to filter
for views that don't correspond to the matcher, as
shown in the following example:
</p>
<pre> <pre>
onView(allOf(withId(R.id.button_signin), not(withText("Sign-out")))); onView(allOf(withId(R.id.button_signin), not(withText("Sign-out"))));
</pre> </pre>
<p>To use these methods in your test, import the {@code org.hamcrest.Matchers} package. To
<p>
To use these methods in your test,
import the {@code org.hamcrest.Matchers} package. To
learn more about Hamcrest matching, see the learn more about Hamcrest matching, see the
<a href="http://hamcrest.org/" class="external-link">Hamcrest site</a>. <a href="http://hamcrest.org/" class="external-link">Hamcrest site</a>.
</p> </p>
@@ -399,66 +406,78 @@ learn more about Hamcrest matching, see the
</ul> </ul>
<p> <p>
To improve the performance of your Espresso tests, specify the minimum matching information To improve the performance of your Espresso tests,
needed to find your target view. For example, if a view is uniquely identifiable by its specify the minimum matching information
descriptive text, you do not need to specify that it is also assignable from the 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
{@link android.widget.TextView} instance. {@link android.widget.TextView} instance.
</p> </p>
<!-- Section 2.2.2 -->
<h4 id="#locating-adpeterview-view"> <h4 id="#locating-adpeterview-view">
Locating a view in an AdapterView Locating a view in an AdapterView
</h4> </h4>
<p> <p>
In an {@link android.widget.AdapterView} widget, the view is dynamically populated with child In an {@link android.widget.AdapterView} widget,
the view is dynamically populated with child
views at runtime. If the target view you want to test is inside an views at runtime. If the target view you want to test is inside an
{@link android.widget.AdapterView} {@link android.widget.AdapterView}
(such as a {@link android.widget.ListView}, {@link android.widget.GridView}, or (such as a {@link android.widget.ListView},
{@link android.widget.GridView}, or
{@link android.widget.Spinner}), the {@link android.widget.Spinner}), the
<a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onView(org.hamcrest.Matcher<android.view.View>)"> <a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onView(org.hamcrest.Matcher<android.view.View>)">{@code onView()}</a>
{@code onView()}</a> method might not work because only a method might not work because only a
subset of the views may be loaded in the current view hierarchy. subset of the views may be loaded in the current view hierarchy.
</p> </p>
<p> <p>
Instead, call the <a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onData(org.hamcrest.Matcher<java.lang.Object>)">{@code onData()}</a> Instead, call the
<a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onData(org.hamcrest.Matcher<java.lang.Object>)">{@code onData()}</a>
method to obtain a method to obtain a
<a href="{@docRoot}reference/android/support/test/espresso/DataInteraction.html"> <a href="{@docRoot}reference/android/support/test/espresso/DataInteraction.html">{@code DataInteraction}</a>
{@code DataInteraction}</a> object to access the target view element.
object to access the target view element. Espresso handles loading 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, into the current view hierarchy. Espresso
also takes care of scrolling to the target element,
and putting the element into focus. and putting the element into focus.
</p> </p>
<p class="note"> <p class="note">
<strong>Note</strong>: The <strong>Note</strong>: The
<a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onData(org.hamcrest.Matcher<java.lang.Object>)">{@code onData()}</a> <a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onData(org.hamcrest.Matcher<java.lang.Object>)">{@code onData()}</a>
method does not check if if the item you specified corresponds with a view. Espresso searches 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 only the current view hierarchy. If no match is found, the method throws a
<a href="{@docRoot}reference/android/support/test/espresso/NoMatchingViewException.html"> <a href="{@docRoot}reference/android/support/test/espresso/NoMatchingViewException.html">{@code NoMatchingViewException}</a>.
{@code NoMatchingViewException}</a>.
</p> </p>
<p> <p>
The following code snippet shows how you can use the The following code snippet shows how you can use the
<a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onData(org.hamcrest.Matcher<java.lang.Object>)">{@code onData()}</a> <a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onData(org.hamcrest.Matcher<java.lang.Object>)">{@code onData()}</a>
method together method together
with Hamcrest matching to search for a specific row in a list that contains a given string. with Hamcrest matching to search for a specific
In this example, the {@code LongListActivity} class contains a list of strings exposed row in a list that contains a given string.
In this example, the {@code LongListActivity} class
contains a list of strings exposed
through a {@link android.widget.SimpleAdapter}. through a {@link android.widget.SimpleAdapter}.
</p> </p>
<pre> <pre>
onData(allOf(is(instanceOf(Map.class)), onData(allOf(is(instanceOf(Map.class)),
hasEntry(equalTo(LongListActivity.ROW_TEXT), is(str)))); hasEntry(equalTo(LongListActivity.ROW_TEXT), is("test input")));
</pre> </pre>
<h3 id="perform-actions"> <!-- Section 2.3 -->
Performing Actions
</h3> <h3 id="perform-actions">Performing Actions</h3>
<p> <p>
Call the <a href="{@docRoot}reference/android/support/test/espresso/ViewInteraction.html#perform(android.support.test.espresso.ViewAction...)">{@code ViewInteraction.perform()}</a> Call the
<a href="{@docRoot}reference/android/support/test/espresso/ViewInteraction.html#perform(android.support.test.espresso.ViewAction...)">{@code ViewInteraction.perform()}</a>
or or
<a href="{@docRoot}reference/android/support/test/espresso/DataInteraction.html#perform(android.support.test.espresso.ViewAction...)">{@code DataInteraction.perform()}</a> <a href="{@docRoot}reference/android/support/test/espresso/DataInteraction.html#perform(android.support.test.espresso.ViewAction...)">{@code DataInteraction.perform()}</a>
methods to methods to
@@ -472,8 +491,9 @@ onData(allOf(is(instanceOf(Map.class)),
The The
<a href="{@docRoot}reference/android/support/test/espresso/action/ViewActions.html">{@code ViewActions}</a> <a href="{@docRoot}reference/android/support/test/espresso/action/ViewActions.html">{@code ViewActions}</a>
class provides a list of helper methods for specifying common actions. class provides a list of helper methods for specifying common actions.
You can use these methods as convenient shortcuts instead of creating and configuring You can use these methods as convenient shortcuts
individual <a href="{@docRoot}reference/android/support/test/espresso/ViewAction.html">{@code ViewAction}</a> instead of creating and configuring individual
<a href="{@docRoot}reference/android/support/test/espresso/ViewAction.html">{@code ViewAction}</a>
objects. You can specify such actions as: objects. You can specify such actions as:
</p> </p>
@@ -496,8 +516,7 @@ onData(allOf(is(instanceOf(Map.class)),
<a href="http://developer.android.com/reference/android/view/View.html#attr_android:visibility">{@code android:visibility}</a> <a href="http://developer.android.com/reference/android/view/View.html#attr_android:visibility">{@code android:visibility}</a>
property must be {@link android.view.View#VISIBLE}. For views that extend property must be {@link android.view.View#VISIBLE}. For views that extend
{@link android.widget.AdapterView} (for example, {@link android.widget.AdapterView} (for example,
{@link android.widget.ListView}), {@link android.widget.ListView}), the
the
<a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onData(org.hamcrest.Matcher<java.lang.Object>)">{@code onData()}</a> <a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onData(org.hamcrest.Matcher<java.lang.Object>)">{@code onData()}</a>
method takes care of scrolling for you. method takes care of scrolling for you.
</li> </li>
@@ -514,7 +533,8 @@ onData(allOf(is(instanceOf(Map.class)),
</ul> </ul>
<p> <p>
If the target view is inside a {@link android.widget.ScrollView}, perform the If the target view is inside a {@link android.widget.ScrollView},
perform the
<a href="{@docRoot}reference/android/support/test/espresso/action/ViewActions.html#scrollTo()">{@code ViewActions.scrollTo()}</a> <a href="{@docRoot}reference/android/support/test/espresso/action/ViewActions.html#scrollTo()">{@code ViewActions.scrollTo()}</a>
action first to display the view in the screen before other proceeding action first to display the view in the screen before other proceeding
with other actions. The with other actions. The
@@ -522,6 +542,207 @@ onData(allOf(is(instanceOf(Map.class)),
action will have no effect if the view is already displayed. action will have no effect if the view is already displayed.
</p> </p>
<!-- Section 2.4 -->
<h3 id="intents">
Test your activities in isolation with Espresso Intents
</h3>
<p>
<a href="https://google.github.io/android-testing-support-library/docs/espresso/intents/index.html" class="external-link">Espresso Intents</a>
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.
</p>
<p>
To begin testing with Espresso Intents, you need
to add the following line to your app's build.gradle file:
</p>
<pre>
dependencies {
// Other dependencies ...
androidTestCompile 'com.android.support.test.espresso:espresso-intents:2.2.2'
}
</pre>
<p>
To test an intent, you need to create an instance of the
<a href="{@docRoot}reference/android/support/test/espresso/intent/rule/IntentsTestRule.html">IntentsTestRule</a>
class, which is very similar to the
<a href="{@docRoot}reference/android/support/test/rule/ActivityTestRule.html">ActivityTestRule</a>
class.
The
<a href="{@docRoot}reference/android/support/test/espresso/intent/rule/IntentsTestRule.html">IntentsTestRule</a>
class initializes Espresso Intents before each test,
terminates the host activity,
and releases Espresso Intents after each test.
</p>
<p>
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
<a href="{@docRoot}training/basics/firstapp/index.html">Building Your First App</a>
tutorial.
</p>
<pre>
&#64;Large
&#64;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 IntentsTestRule object. */
&#64;Rule
public IntentsTestRule&lg;MainActivity&gt; mIntentsRule =
new IntentsTestRule&lg;&gt;(MainActivity.class);
&#64;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)));
}
}
</pre>
<p>
For more information about Espresso Intents, see the
<a href="https://google.github.io/android-testing-support-library/docs/espresso/intents/index.html"
class="external-link">Espresso Intents
documentation on the Android Testing Support Library site</a>.
You can also download the
<a href="https://github.com/googlesamples/android-testing/tree/master/ui/espresso/IntentsBasicSample"
class="external-link">IntentsBasicSample</a> and
<a href="https://github.com/googlesamples/android-testing/tree/master/ui/espresso/IntentsAdvancedSample"
class="external-link">IntentsAdvancedSample</a>
code samples.
</p>
<!-- Section 2.5 -->
<h3 id="webviews">
Testing WebViews with Espresso Web
</h3>
<p>
Espresso Web allows you to test {@link android.webkit.WebView} components
contained within an activity. It uses the
<a href="http://docs.seleniumhq.org/docs/03_webdriver.jsp"
class="external-link">WebDriver API</a> to inspect and control the
behavior of a {@link android.webkit.WebView}.
</p>
<p>
To begin testing with Espresso Web, you need
to add the following line to your app's build.gradle file:
</p>
<pre>
dependencies {
// Other dependencies ...
androidTestCompile 'com.android.support.test.espresso:espresso-web:2.2.2'
}
</pre>
<p>
When creating a test using Espresso Web, you need to enable
JavaScript on the {@link android.webkit.WebView} when you instantiate the
<a href="{@docRoot}reference/android/support/test/rule/ActivityTestRule.html">ActivityTestRule</a>
object to test the activity. In the tests, you can select
HTML elements displayed in the
{@link android.webkit.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.
</p>
<p>
In the following code snippet, the class tests
a {@link android.webkit.WebView} component with the id value 'webview'
in the activity being tested.
The <code>verifyValidInputYieldsSuccesfulSubmission()</code> test selects an
<code>&lt;input&gt;</code> element on the
Web page, enters some text, and checks text that appears in
another element.
</p>
<pre>
&#64;LargeTest
&#64;RunWith(AndroidJUnit4.class)
public class WebViewActivityTest {
private static final String MACCHIATO = "Macchiato";
private static final String DOPPIO = "Doppio";
&#64;Rule
public ActivityTestRule<WebViewActivity> mActivityRule =
new ActivityTestRule<WebViewActivity>(WebViewActivity.class,
false /* Initial touch mode */, false /* launch activity */) {
&#64;Override
protected void afterActivityLaunched() {
// Enable JavaScript.
onWebView().forceJavascriptEnabled();
}
}
&#64;Test
public void typeTextInInput_clickButton_SubmitsForm() {
// Lazily launch the Activity with a custom start Intent per test
mActivityRule.launchActivity(withWebFormIntent());
// 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)));
}
}
</pre>
<p>
For more information about Espresso Web, see the
<a href="https://google.github.io/android-testing-support-library/docs/espresso/web/index.html"
class="external-link">Espresso
Web documentation on the Android Testing Support Library site.</a>.
You can also download this code snippet as part of the
<a href="https://github.com/googlesamples/android-testing/tree/master/ui/espresso/WebBasicSample"
class="external-link">Espresso Web code sample</a>.
</p>
<!-- Section 2.6 -->
<h3 id="verify-results"> <h3 id="verify-results">
Verifying Results Verifying Results
</h3> </h3>
@@ -533,8 +754,8 @@ onData(allOf(is(instanceOf(Map.class)),
<a href="{@docRoot}reference/android/support/test/espresso/DataInteraction.html#check(android.support.test.espresso.ViewAssertion)">{@code DataInteraction.check()}</a> <a href="{@docRoot}reference/android/support/test/espresso/DataInteraction.html#check(android.support.test.espresso.ViewAssertion)">{@code DataInteraction.check()}</a>
method to assert method to assert
that the view in the UI matches some expected state. You must pass in a that the view in the UI matches some expected state. You must pass in a
<a href="{@docRoot}reference/android/support/test/espresso/ViewAssertion.html"> <a href="{@docRoot}reference/android/support/test/espresso/ViewAssertion.html">{@code ViewAssertion}</a>
{@code ViewAssertion}</a> object as the argument. If the assertion fails, Espresso throws object as the argument. If the assertion fails, Espresso throws
an {@link junit.framework.AssertionFailedError}. an {@link junit.framework.AssertionFailedError}.
</p> </p>
@@ -548,7 +769,8 @@ onData(allOf(is(instanceOf(Map.class)),
<ul> <ul>
<li> <li>
<a href="{@docRoot}reference/android/support/test/espresso/assertion/ViewAssertions.html#doesNotExist()">{@code doesNotExist}</a>: <a href="{@docRoot}reference/android/support/test/espresso/assertion/ViewAssertions.html#doesNotExist()">{@code doesNotExist}</a>:
Asserts that there is no view matching the specified criteria in the current view hierarchy. Asserts that there is no view matching the specified
criteria in the current view hierarchy.
</li> </li>
<li> <li>
@@ -558,17 +780,19 @@ Asserts that there is no view matching the specified criteria in the current vie
</li> </li>
<li> <li>
<a href="{@docRoot}reference/android/support/test/espresso/assertion/ViewAssertions.html#selectedDescendantsMatch(org.hamcrest.Matcher&lt;android.view.View&gt;, org.hamcrest.Matcher&lt;android.view.View&gt;)">{@code selectedDescendentsMatch}</a> <a href="{@docRoot}reference/android/support/test/espresso/assertion/ViewAssertions.html#selectedDescendantsMatch(org.hamcrest.Matcher&lt;android.view.View&gt;, org.hamcrest.Matcher&lt;android.view.View&gt;)">{@code selectedDescendentsMatch}</a>:
: Asserts that the specified children views for a Asserts that the specified children views for a
parent view exist, and their state matches some given Hamcrest matcher. parent view exist, and their state matches some given Hamcrest matcher.
</li> </li>
</ul> </ul>
<p> <p>
The following code snippet shows how you might check that the text displayed in the UI has 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 the same value as the text previously entered in the
{@link android.widget.EditText} field. {@link android.widget.EditText} field.
</p> </p>
<pre> <pre>
public void testChangeText_sameActivity() { public void testChangeText_sameActivity() {
// Type text and then press the button. // Type text and then press the button.
@@ -580,14 +804,22 @@ public void testChangeText_sameActivity() {
} }
</pre> </pre>
<h2 id="run">Run Espresso Tests on a Device or Emulator</h2> <!-- Section 3 -->
<h2 id="run">
Run Espresso Tests on a Device or Emulator
</h2>
<p> <p>
You can run Espresso tests from <a href="{@docRoot}studio/index.html">Android Studio</a> or You can run Espresso tests from
<a href="{@docRoot}studio/index.html">Android Studio</a> or
from the command-line. Make sure to specify from the command-line. Make sure to specify
<a href="{@docRoot}reference/android/support/test/runner/AndroidJUnitRunner.html"> <a href="{@docRoot}reference/android/support/test/runner/AndroidJUnitRunner.html">{@code AndroidJUnitRunner}</a>
{@code AndroidJUnitRunner}</a> as the default instrumentation runner in your project. as the default instrumentation runner in your project.
</p> </p>
<p> <p>
To run your Espresso test, follow the steps for running instrumented tests To run your Espresso test, follow the steps for running instrumented tests
described in <a href="{@docRoot}training/testing/start/index.html#run-instrumented-tests"> described in
Getting Started with Testing</a>.</p> <a href="{@docRoot}training/testing/start/index.html#run-instrumented-tests">Getting Started with Testing</a>.
</p>