1page.title=Testing Support Library
2
3@jd:body
4
5  <div id="qv-wrapper">
6    <div id="qv">
7    <h2>
8      In this document
9    </h2>
10
11    <ol>
12      <li>
13      <a href="#features">Testing Support Library Features</a>
14      <ol>
15        <li>
16        <a href="#AndroidJUnitRunner">AndroidJUnitRunner</a>
17        </li>
18
19        <li>
20        <a href="#Espresso">Espresso</a>
21        </li>
22
23        <li>
24        <a href="#UIAutomator">UI Automator</a>
25        </li>
26      </ol>
27      </li>
28
29      <li>
30      <a href="#setup">Testing Support Library Setup</a>
31      </li>
32    </ol>
33
34    <h2>See also</h2>
35  <ol>
36    <li><a href="{@docRoot}reference/android/support/test/package-summary.html">
37      Testing Support Library API Reference</a></li>
38    <li><a href="https://github.com/googlesamples/android-testing" class="external-link">
39      Code Samples</a></li>
40  </ol>
41    </div>
42  </div>
43
44  <p>
45    The Android Testing Support Library provides an extensive framework for testing Android apps.
46    This library provides a set of APIs that allow you to quickly build and run test code for
47    your apps, including JUnit 4 and functional user interface (UI) tests. You can run tests
48    created using these APIs from the <a href=
49    "{@docRoot}tools/studio/index.html">Android Studio IDE</a> or from the command line.
50  </p>
51
52  <p>The Android Testing Support library is available through the Android SDK Manager.
53    For more information, see <a href="#setup">Testing Support Library Setup</a>
54  </p>
55
56  <p>
57    This page provides information about what tools are provided in the Android Testing Support
58    Library, how to use them in your testing environment, and information about library releases.
59  </p>
60
61  <h2 id="features">
62    Testing Support Library Features
63  </h2>
64
65  <p>
66    The Android Testing Support Library includes the following test automation tools:
67  </p>
68
69  <ul>
70    <li>
71    <strong><a href="#AndroidJUnitRunner">AndroidJUnitRunner</a></strong>: JUnit 4-compatible
72    test runner for Android
73    </li>
74
75    <li>
76    <strong><a href="#Espresso">Espresso</a></strong>: UI testing framework; suitable for
77    functional UI testing within an app
78    </li>
79
80    <li>
81    <strong><a href="#UIAutomator">UI Automator</a></strong>: UI testing framework; suitable
82    for cross-app functional UI testing across system and installed apps
83    </li>
84  </ul>
85
86  <h3 id="AndroidJUnitRunner">
87    AndroidJUnitRunner
88  </h3>
89
90  <p>
91    The
92    <a href="{@docRoot}reference/android/support/test/runner/AndroidJUnitRunner.html">{@code AndroidJUnitRunner}</a>
93    class is a <a href="http://junit.org/" class="external-link">JUnit</a> test runner that lets you
94    run JUnit 3 or JUnit 4-style test classes on Android devices, including those using the
95    <a href="#Espresso">Espresso</a> and <a href="#UIAutomator">UI Automator</a> testing frameworks.
96    The test runner handles loading your test package and the app under test
97    to a device, running your tests, and reporting test results. This class replaces the {@link
98    android.test.InstrumentationTestRunner} class, which only supports JUnit 3 tests.
99  </p>
100
101  <p>
102    The key features of this test runner include:
103  </p>
104
105  <ul>
106    <li><a href="#ajur-junit">JUnit support</a>
107    </li>
108
109    <li><a href="#ajur-instrumentation">Access to instrumentation information</a>
110    </li>
111
112    <li><a href="#ajur-filtering">Test filtering</a>
113    </li>
114
115    <li><a href="#ajur-sharding">Test sharding</a>
116    </li>
117  </ul>
118
119  <p>Requires Android 2.2 (API level 8) or higher.</p>
120
121  <h4 id="ajur-junit">
122    JUnit support
123  </h4>
124
125  <p>
126    The test runner is compatible with your JUnit 3 and JUnit 4 (up to JUnit
127    4.10) tests. However, you should avoid mixing JUnit 3 and and JUnit 4 test code in the same
128    package, as this might cause unexpected results. If you are creating an instrumented JUnit 4
129    test class to run on a device or emulator, your test class must be prefixed with the
130    {@code &#64;RunWith(AndroidJUnit4.class)} annotation.
131  </p>
132
133  <p>The following code snippet shows how you might write an instrumented JUnit 4 test to validate
134    that the <em>add</em> operation in the {@code CalculatorActivity} class works correctly.
135</p>
136
137<pre>
138import android.support.test.runner.AndroidJUnit4;
139import android.support.test.runner.AndroidJUnitRunner;
140import android.test.ActivityInstrumentationTestCase2;
141
142&#64;RunWith(AndroidJUnit4.class)
143public class CalculatorInstrumentationTest
144        extends ActivityInstrumentationTestCase2&lt;CalculatorActivity&gt; {
145
146    &#64;Before
147    public void setUp() throws Exception {
148        super.setUp();
149
150        // Injecting the Instrumentation instance is required
151        // for your test to run with AndroidJUnitRunner.
152        injectInstrumentation(InstrumentationRegistry.getInstrumentation());
153        mActivity = getActivity();
154    }
155
156    &#64;Test
157    public void typeOperandsAndPerformAddOperation() {
158        // Call the CalculatorActivity add() method and pass in some operand values, then
159        // check that the expected value is returned.
160    }
161
162    &#64;After
163    public void tearDown() throws Exception {
164        super.tearDown();
165    }
166}
167</pre>
168
169  <h4 id="ajur-instrumentation">
170    Access to instrumentation information
171  </h4>
172
173  <p>
174    You can use the
175    <a href="{@docRoot}reference/android/support/test/InstrumentationRegistry.html">{@code InstrumentationRegistry}</a>
176    class to access information related to your
177    test run. This class includes the {@link android.app.Instrumentation} object, target app {@link
178    android.content.Context} object, test app {@link android.content.Context} object, and the
179    command line arguments passed into your test. This data is useful when you are writing tests
180    using the UI Automator framework or when writing tests that have dependencies on the {@link
181    android.app.Instrumentation} or {@link android.content.Context} objects.
182  </p>
183
184  <h4 id="ajur-filtering">
185    Test filtering
186  </h4>
187
188  <p>
189    In your JUnit 4.x tests, you can use annotations to configure the test run. This feature
190    minimizes the need to add boilerplate and conditional code in your tests. In addition to the
191    standard annotations supported by JUnit 4, the test runner  also supports Android-specific
192    annotations, including:
193  </p>
194
195  <ul>
196    <li><a href="{@docRoot}reference/android/support/test/filters/RequiresDevice.html">{@code &#64;RequiresDevice}</a>:
197    Specifies that the test should run only on physical devices, not on emulators.
198    </li>
199
200    <li><a href="{@docRoot}reference/android/support/test/filters/SdkSuppress.html">{@code &#64;SdkSupress}</a>:
201    Suppresses the test from running on a lower Android API level than the given level. For
202    example, to suppress tests on all API levels lower than 18 from running, use the annotation
203    {@code &#64;SDKSupress(minSdkVersion=18)}.
204    </li>
205
206    <li>{@link android.test.suitebuilder.annotation.SmallTest &#64;SmallTest},
207      {@link android.test.suitebuilder.annotation.MediumTest &#64;MediumTest},
208      and {@link android.test.suitebuilder.annotation.LargeTest &#64;LargeTest}: Classify how long
209      a test should take to run, and consequently, how frequently you can run the test.
210    </li>
211  </ul>
212
213  <h4 id="ajur-sharding">
214    Test sharding
215  </h4>
216
217  <p>
218    The test runner supports splitting a single test suite into multiple
219    <em>shards</em>, so you can easily run tests belonging to the same shard together as a group,
220    under the same {@link android.app.Instrumentation} instance. Each shard is identified by an
221    index number. When running tests, use the {@code -e numShards} option to specify the number
222    of separate shards to create and the {@code -e shardIndex} option to specify which shard to
223    run.
224  </p>
225
226  <p>
227    For example, to split the test suite into 10 shards and run only the tests grouped in the
228    second shard, use the following command:
229  </p>
230
231  <pre>
232adb shell am instrument -w -e numShards 10 -e shardIndex 2</pre>
233
234  <p>
235    To learn more about using this test runner, see the
236    <a href="{@docRoot}reference/android/support/test/package-summary.html">API reference</a>.
237  </p>
238
239  <h3 id="Espresso">
240    Espresso
241  </h3>
242
243  <p>
244    The Espresso testing framework provides a set of APIs to build UI tests to test user flows
245    within an app. These APIs let you write automated UI tests that are concise and that run
246    reliably. Espresso is well-suited for writing <em>white box</em>-style automated tests, where
247    the test code utilizes implementation code details from the app under test.
248  </p>
249
250  <p>
251    The key features of the Espresso testing framework include:
252  </p>
253
254  <ul>
255    <li>Flexible APIs for view and adapter matching in target apps.
256      For more information, see <a href="#espresso-matching">View matching</a>.
257
258    <li>An extensive set of action APIs to automate UI interactions.
259      For more information, see <a href="#espresso-actions">Action APIs</a>.
260    </li>
261
262    <li>UI thread synchronization to improve test reliability.
263      For more information, see <a href="#espresso-thread-sync">UI thread synchronization</a>.
264    </li>
265  </ul>
266
267  <p>Requires Android 2.2 (API level 8) or higher.</p>
268
269  <h4 id="espresso-matching">
270    View matching
271  </h4>
272
273  <p>
274    The <a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onView(org.hamcrest.Matcher<android.view.View>)">{@code Espresso.onView()}</a>
275    method lets you access a UI component in the target app and
276    interact with it. The method accepts a
277    <a href="http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matcher.html"
278    class="external-link">{@code Matcher}</a> argument and searches the view
279    hierarchy to locate a corresponding {@link android.view.View} instance that meets some given
280    criteria. You can refine searches by specifying such criteria as:
281  </p>
282
283  <ul>
284    <li>The class name of the view
285    </li>
286
287    <li>The content description of the view
288    </li>
289
290    <li>The {@code R.id} of the view
291    </li>
292
293    <li>Text displayed in the view
294    </li>
295  </ul>
296
297  <p>
298    For example, to target a button that has the ID value of {@code my_button}, you can specify
299    a matcher like this:
300  </p>
301
302  <pre>
303onView(withId(R.id.my_button));</pre>
304
305  <p>
306    If the search is successful, the
307    <a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onView(org.hamcrest.Matcher<android.view.View>)">{@code onView()}</a>
308    method returns a reference which lets you
309    perform user actions and test assertions against the target view.
310  </p>
311
312  <h4>
313    Adapter matching
314  </h4>
315
316  <p>
317    In an {@link android.widget.AdapterView} layout, the layout is dynamically populated with
318    children views at runtime. If the target view is inside a layout subclassed from {@link
319    android.widget.AdapterView} (such as a {@link android.widget.ListView} or {@link
320    android.widget.GridView}), the
321    <a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onView(org.hamcrest.Matcher<android.view.View>)">{@code onView()}</a>
322    method might not work because only a subset of
323    the layout’s views may be loaded in the current view hierarchy.
324  </p>
325
326  <p>
327    Instead, use the <a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onData(org.hamcrest.Matcher<java.lang.Object>)">{@code Espresso.onData()}</a>
328    method to access a target view element. The <a href="{@docRoot}reference/android/support/test/espresso/Espresso.html#onData(org.hamcrest.Matcher<java.lang.Object>)">{@code Espresso.onData()}</a>
329    method returns a reference which lets you perform user actions and test assertions against the
330    elements in an {@link android.widget.AdapterView}.
331  </p>
332
333  <h4 id="espresso-actions">
334    Action APIs
335  </h4>
336
337  <p>
338    Typically, you test an app by performing some user interactions against the app’s user
339    interface. You can easily automate these actions in your test by using the
340    <a href="{@docRoot}reference/android/support/test/espresso/action/ViewActions.html">{@code ViewActions}</a>
341    API. You can perform such UI interactions as:
342  </p>
343
344  <ul>
345    <li>View clicks
346    </li>
347
348    <li>Swipes
349    </li>
350
351    <li>Key and button presses
352    </li>
353
354    <li>Typing text
355    </li>
356
357    <li>Opening a link
358    </li>
359  </ul>
360
361  <p>
362    For example, to simulate entering a string value and pressing a button to submit the value,
363    you can write an automated test script like this. The
364    <a href="{@docRoot}reference/android/support/test/espresso/ViewInteraction.html#perform(android.support.test.espresso.ViewAction...)">{@code ViewInteraction.perform()}</a>
365    and <a href="{@docRoot}reference/android/support/test/espresso/DataInteraction.html#perform(android.support.test.espresso.ViewAction...)">{@code DataInteraction.perform()}</a>
366    methods take one or more
367    <a href="{@docRoot}reference/android/support/test/espresso/ViewAction.html">{@code ViewAction}</a>
368    arguments and run the actions in the order provided.
369  </p>
370
371  <pre>
372// Type text into an EditText view, then close the soft keyboard
373onView(withId(R.id.editTextUserInput))
374    .perform(typeText(STRING_TO_BE_TYPED), closeSoftKeyboard());
375
376// Press the button to submit the text change
377onView(withId(R.id.changeTextBt)).perform(click());</pre>
378
379  <h4 id="espresso-thread-sync">
380    UI thread synchronization
381  </h4>
382
383  <p>
384    Tests on Android devices can fail randomly because of timing issues. This testing issue is
385    referred to as <em>test flakiness</em>. Prior to Espresso, the workaround was to insert a
386    sufficiently long sleep or timeout period into a test or to add code to keep retrying the
387    failing operation. The Espresso testing framework handles synchronization between the
388    {@link android.app.Instrumentation} and the UI thread; this removes the need for the previous
389    timing workarounds and ensures that your test actions and assertions run more reliably.
390  </p>
391
392  <p>
393    To learn more about using Espresso, see the
394    <a href="{@docRoot}reference/android/support/test/package-summary.html">API reference</a> and
395    <a href="{@docRoot}training/testing/ui-testing/espresso-testing.html">
396      Testing UI for a Single App</a> training.
397  </p>
398
399  <h3 id="UIAutomator">
400    UI Automator
401  </h3>
402
403  <p>
404    The UI Automator testing framework provides a set of APIs to build UI tests that perform
405    interactions on user apps and system apps. The UI Automator APIs allows you to perform
406    operations such as opening the Settings menu or the app launcher in a test device. The UI
407    Automator testing framework is well-suited for writing <em>black box</em>-style automated
408    tests, where the test code does not rely on internal implementation details of the target
409    app.
410  </p>
411
412  <p>
413    The key features of the UI Automator testing framework include:
414  </p>
415
416  <ul>
417    <li>A viewer to inspect layout hierarchy.
418      For more information, see <a href="#uia-viewer">UI Automator Viewer</a>.
419    </li>
420    <li>An API to retrieve state information and perform operations on the target device.
421      For more information, see <a href="#uia-device-state">Access to device state</a>.
422    </li>
423    <li>APIs that support cross-app UI testing.
424      For more information, see <a href="#uia-apis">UI Automator APIs</a> .
425    </li>
426  </ul>
427
428  <p>Requires Android 4.3 (API level 18) or higher.</p>
429
430  <h4 id="uia-viewer">
431    UI Automator Viewer
432  </h4>
433
434  <p>
435    The {@code uiautomatorviewer} tool provides a convenient GUI to scan and analyze the UI
436    components currently displayed on an Android device. You can use this tool to inspect the
437    layout hierarchy and view the properties of UI components that are visible on the foreground
438    of the device. This information lets you create more fine-grained tests using UI Automator,
439    for example by creating a UI selector that matches a specific visible property.
440  </p>
441
442  <p>
443    The {@code uiautomatorviewer} tool is located in the {@code &lt;android-sdk&gt;/tools/}
444    directory.
445  </p>
446
447  <h4 id="uia-device-state">
448    Access to device state
449  </h4>
450
451  <p>
452    The UI Automator testing framework provides a
453    <a href="{@docRoot}reference/android/support/test/uiautomator/UiDevice.html">{@code UiDevice}</a>
454    class to access and perform operations on the device on which the target app is running. You
455    can call its methods to access device properties such as current orientation or display size.
456    The <a href="{@docRoot}reference/android/support/test/uiautomator/UiDevice.html">{@code UiDevice}</a>
457    class also let you perform actions such as:
458  </p>
459
460  <ul>
461    <li>Change the device rotation
462    </li>
463
464    <li>Press a D-pad button
465    </li>
466
467    <li>Press the Back, Home, or Menu buttons
468    </li>
469
470    <li>Open the notification shade
471    </li>
472
473    <li>Take a screenshot of the current window
474    </li>
475  </ul>
476
477  <p>
478    For example, to simulate a Home button press, call the {@code UiDevice.pressHome()} method.
479  </p>
480
481  <h4 id="uia-apis">
482    UI Automator APIs
483  </h4>
484
485  <p>
486    The UI Automator APIs allow you to write robust tests without needing to know about the
487    implementation details of the app that you are targeting. You can use these APIs to capture
488    and manipulate UI components across multiple apps:
489  </p>
490
491  <ul>
492    <li><a href="{@docRoot}reference/android/support/test/uiautomator/UiCollection.html">{@code UiCollection}</a>:
493      Enumerates a container's UI elements for the purpose of counting,
494    or targeting sub-elements by their visible text or content-description property.
495    </li>
496
497    <li><a href="{@docRoot}reference/android/support/test/uiautomator/UiObject.html">{@code UiObject}</a>:
498      Represents a UI element that is visible on the device.
499    </li>
500
501    <li><a href="{@docRoot}reference/android/support/test/uiautomator/UiScrollable.html">{@code UiScrollable}</a>:
502      Provides support for searching for items in a scrollable UI container.
503    </li>
504
505    <li><a href="{@docRoot}reference/android/support/test/uiautomator/UiSelector.html">{@code UiSelector}</a>:
506      Represents a query for one or more target UI elements on a device.
507    </li>
508
509    <li><a href="{@docRoot}reference/android/support/test/uiautomator/Configurator.html">{@code Configurator}</a>:
510      Allows you to set key parameters for running UI Automator tests.
511    </li>
512  </ul>
513
514  <p>
515    For example, the following code shows how you can write a test script that brings up the
516    default app launcher in the device:
517  </p>
518
519  <pre>
520// Initialize UiDevice instance
521mDevice = UiDevice.getInstance(getInstrumentation());
522
523// Perform a short press on the HOME button
524mDevice().pressHome();
525
526// Bring up the default launcher by searching for
527// a UI component that matches the content-description for the launcher button
528UiObject allAppsButton = mDevice
529        .findObject(new UiSelector().description("Apps"));
530
531// Perform a click on the button to bring up the launcher
532allAppsButton.clickAndWaitForNewWindow();</pre>
533
534  <p>
535    To learn more about using UI Automator, see the
536    <a href="{@docRoot}reference/android/support/test/package-summary.html">API reference</a> and
537    <a href="{@docRoot}training/testing/ui-testing/uiautomator-testing.html">
538      Testing UI for Multiple Apps</a> training.
539  </p>
540
541  <h2 id="setup">
542    Testing Support Library Setup
543  </h2>
544
545  <p>
546    The Android Testing Support Library package is included with the latest version of the
547    Android Support Repository, which you can obtain as a supplemental download through the
548    Android SDK Manager.
549  </p>
550
551  <p>
552    To download the Android Support Repository through the SDK Manager:
553  </p>
554
555  <ol>
556    <li>Start the <a href="{@docRoot}tools/help/sdk-manager.html">Android SDK Manager</a>.
557    </li>
558
559    <li>In the SDK Manager window, scroll to the end of the <i>Packages</i> list, find the
560    <em>Extras</em> folder and, if necessary, expand to show its contents.
561    </li>
562
563    <li>Select the <strong>Android Support Repository</strong> item.
564    </li>
565
566    <li>Click the <strong>Install packages...</strong> button.
567    </li>
568  </ol>
569
570  <p>
571    After downloading, the tool installs the Support Repository files to your existing Android
572    SDK directory. The library files are located in the following subdirectory of your SDK:
573    {@code &lt;sdk&gt;/extras/android/m2repository} directory.
574  </p>
575
576  <p>
577    The Android Testing Support Library classes are located under the
578    {@code android.support.test} package.
579  </p>
580
581  <p>
582    To use the Android Testing Support Library in your Gradle project, add these dependencies in
583    your {@code build.gradle} file:
584  </p>
585
586  <pre>
587dependencies {
588  androidTestCompile 'com.android.support.test:runner:0.3'
589  // Set this dependency to use JUnit 4 rules
590  androidTestCompile 'com.android.support.test:rules:0.3'
591  // Set this dependency to build and run Espresso tests
592  androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2'
593  // Set this dependency to build and run UI Automator tests
594  androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.1'
595}</pre>
596
597  <p>To set
598<a href="{@docRoot}reference/android/support/test/runner/AndroidJUnitRunner.html">{@code AndroidJUnitRunner}</a>
599  as the default test instrumentation runner in your Gradle project, specify this dependency in
600  your {@code build.gradle} file:</p>
601
602  <pre>
603android {
604    defaultConfig {
605        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
606    }
607}</pre>
608
609  <p>
610    It is strongly recommended that you use the Android Testing Support Library together with the
611    Android Studio IDE. Android Studio offers capabilities that support test
612    development, such as:
613  </p>
614
615  <ul>
616    <li>Flexible Gradle-based build system that supports dependency management for your test code
617    </li>
618
619    <li>Single project structure to contain your unit and instrumented test code together with
620    your app source code
621    </li>
622
623    <li>Support for deploying and running tests on virtual or physical devices, from a
624    command line or graphical user interface
625    </li>
626  </ul>
627
628  <p>
629  For more information about Android Studio and to download it, see
630  <a href="{@docRoot}sdk/index.html">Download Android Studio and SDK Tools</a>.
631  </p>