diff --git a/docs/html/tools/testing-support-library/index.jd b/docs/html/tools/testing-support-library/index.jd index aeace8e5064ae..c8c9ef5c78fb0 100644 --- a/docs/html/tools/testing-support-library/index.jd +++ b/docs/html/tools/testing-support-library/index.jd @@ -391,7 +391,9 @@ onView(withId(R.id.changeTextBt)).perform(click());
To learn more about using Espresso, see the - API reference. + API reference and + + Testing UI for a Single App training.
To learn more about using UI Automator, see the - API reference. + API reference and + + Testing UI for Multiple Apps training.
+ UI tests that involve user interactions + within a single app help 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 the + Android Testing Support Library, + provides APIs for writing UI tests to simulate user interactions within a + single target app. Espresso tests can run on devices running Android 2.2 (API level 8) 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 adding any timing workarounds, + such as a sleep period, in your test code. +
+ ++ The Espresso testing framework is an instrumentation-based API and works + with the + {@code + AndroidJUnitRunner} test runner. +
+ ++ Before you begin using Espresso, you must: +
+ +app/src/androidTest folder. To
+ learn more about setting up your project directory, see
+ Managing Projects.
+
+dependencies {
+ androidTestCompile 'com.android.support.test:testing-support-lib:0.1'
+ androidTestCompile 'com.android.support.test.espresso:espresso-core:2.0'
+}
+
+ + To create an Espresso test, create a Java class or an + {@link android.test.ActivityInstrumentationTestCase2} + subclass that follows this programming model: +
+ ++ 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: +
+ ++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 ++ +
+ 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 + {@code AndroidJUnitRunner} + test runner. +
+ ++ To do this, call the + {@link android.test.InstrumentationTestCase#injectInstrumentation(android.app.Instrumentation) injectInstrumentation()} + method and pass in the result of + + {@code InstrumentationRegistry.getInstrumentation()}, as shown in the following code + example: +
+ +
+import android.support.test.InstrumentationRegistry;
+
+public class MyEspressoTest
+ extends ActivityInstrumentationTestCase2<MyActivity> {
+
+ private MyActivity mActivity;
+
+ public MyEspressoTest() {
+ super(MyActivity.class);
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ super.setUp();
+ injectInstrumentation(InstrumentationRegistry.getInstrumentation());
+ mActivity = getActivity();
+ }
+
+ ...
+}
+
+
+Note: Previously, {@link android.test.InstrumentationTestRunner} +would inject the {@link android.app.Instrumentation} instance, but this test runner is being +deprecated.
+ ++ 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 + {@code onView()} + method and pass in a view matcher that specifies the view that you are targeting. This is + described in more detail in Specifying a View Matcher. + The + {@code onView()} method returns a + + {@code ViewInteraction} + object that allows your test to interact with the view. + However, calling the + {@code onView()} method may not work if you want to locate a view in + an {@link android.widget.AdapterView} layout. In this case, follow the instructions in + Locating a view in an AdapterView instead. +
+ ++ Note: The + {@code 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 + + {@code NoMatchingViewException}. +
+ ++ 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, + and then performs a button click. +
+ +
+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.
+ ...
+}
+
+
+ + You can specify a view matcher by using these approaches: +
+ +
+onView(withText("Sign-in"));
+
+
+Similarly you can call + +{@code withId()} and providing the resource ID ({@code R.id}) of the view, as shown in the +following example:
+ ++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 + + {@code AmbiguousViewMatcherException}. +
+
+onView(allOf(withId(R.id.button_signin), withText("Sign-in")));
+
+You can use the {@code not} keyword to filter for views that don't correspond to the matcher, as +shown in the following example:
+
+onView(allOf(withId(R.id.button_signin), not(withText("Sign-out"))));
+
+To use these methods in your test, import the {@code 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 + {@link android.widget.TextView} instance. +
+ ++ 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 + {@link android.widget.AdapterView} + (such as a {@link android.widget.ListView}, {@link android.widget.GridView}, or + {@link android.widget.Spinner}), the + + {@code onView()} method might not work because only a + subset of the views may be loaded in the current view hierarchy. +
+ ++ Instead, call the {@code onData()} + method to obtain a + + {@code 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 + {@code onData()} + method does not check if 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 + + {@code NoMatchingViewException}. +
+ ++ The following code snippet shows how you can use the + {@code onData()} + method together + with Hamcrest matching to search for a specific 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}. +
+ ++onData(allOf(is(instanceOf(Map.class)), + hasEntry(equalTo(LongListActivity.ROW_TEXT), is(str)))); ++ +
+ Call the {@code ViewInteraction.perform()} + or + {@code DataInteraction.perform()} + methods to + simulate user interactions on the UI component. You must pass in one or more + {@code ViewAction} + objects as arguments. Espresso fires each action in sequence according to + the given order, and executes them in the main thread. +
+ ++ The + {@code 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 {@code ViewAction} + objects. You can specify such actions as: +
+ ++ If the target view is inside a {@link android.widget.ScrollView}, perform the + {@code ViewActions.scrollTo()} + action first to display the view in the screen before other proceeding + with other actions. The + {@code ViewActions.scrollTo()} + action will have no effect if the view is already displayed. +
+ ++ Call the + {@code ViewInteraction.check()} + or + {@code DataInteraction.check()} + method to assert + that the view in the UI matches some expected state. You must pass in a + + {@code ViewAssertion} object as the argument. If the assertion fails, Espresso throws + an {@link junit.framework.AssertionFailedError}. +
+ ++ The + {@code ViewAssertions} + class provides a list of helper methods for specifying common + assertions. The assertions you can use include: +
+ ++ 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 + {@link android.widget.EditText} field. +
+
+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)));
+}
+
+
++ To run Espresso tests, you must use the + {@code AndroidJUnitRunner} + class provided in the + + Android Testing Support Library as your default test runner. The + Android Plug-in for + Gradle provides a default directory ({@code src/androidTest/java}) for you to store the + instrumented test classes and test suites that you want to run on a device. The + plug-in compiles the test code in that directory and then executes the test app using + the configured test runner class. +
+ ++ To run Espresso tests in your Gradle project: +
+ +
+android {
+ defaultConfig {
+ testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
+ }
+}
+ +./gradlew cC+
User interface (UI) testing lets you ensure that your app meets its functional requirements +and achieves a high standard of quality such that it is more likely to be successfully adopted by +users.
+ +One approach to UI testing is to simply have a human tester perform a set of user operations on +the target app and verify that it is behaving correctly. However, this manual approach can be +time-consuming, tedious, and error-prone. A more efficient approach is to write your UI +tests such that user actions are performed in an automated way. The automated approach allows +you to run your tests quickly and reliably in a repeatable manner.
+ +Note: It is strongly encouraged that you use +Android Studio for +building your test apps, because it provides project setup, library inclusion, and packaging +conveniences. This class assumes you are using Android Studio.
+ +To automate UI tests with Android Studio, you implement your test code in a separate +Android test folder ({@code src/androidTest/java}). The +Android +Plug-in for Gradle builds a test app based on your test code, then loads the test app on the +same device as the target app. In your test code, you can use UI testing frameworks to +simulate user interactions on the target app, in order to perform testing tasks that cover specific +usage scenarios.
+ +For testing Android apps, you typically create these types of automated UI tests:
+ +The lessons in this class teach you how to use the tools and APIs in the +Android Testing Support Library +to build these types of automated tests. Before you begin building tests using these +APIs, you must install the Android Testing Support Library, as described in +Downloading the Android +Testing Support Library.
+ +A user interface (UI) test that involves user interactions across multiple apps lets you +verify that your app behaves correctly when the user flow crosses into other apps or into the +system UI. An example of such a user flow is a messaging app that lets the user enter a text +message, launches the Android contact picker so that the users can select recipients to send the +message to, and then returns control to the original app for the user to submit the message.
+ +This lesson covers how to write such UI tests using the +UI Automator testing framework provided by the +Android Testing Support Library. +The UI Automator APIs let you interact with visible elements on a device, regardless of +which {@link android.app.Activity} is in focus. Your test can look up a UI component by using +convenient descriptors such as the text displayed in that component or its content description. UI +Automator tests can run on devices running Android 4.3 (API level 18) or higher.
+ +The UI Automator testing framework is an instrumentation-based API and works +with the + + {@code AndroidJUnitRunner} +test runner. +
+ +Before you begin using UI Automator, you must:
+ +app/src/androidTest folder.
+ To learn more about setting up your project directory, see
+ Managing Projects.
+
+dependencies {
+ androidTestCompile 'com.android.support.test:testing-support-lib:0.1'
+ androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.0.0'
+}
+
+ To optimize your UI Automator testing, you should first inspect the target app’s UI components +and ensure that they are accessible. These optimization tips are described in the next two +sections.
+ +Before designing your test, inspect the UI components that are visible on the device. To +ensure that your UI Automator tests can access these components, check that these components +have visible text labels, + +{@code android:contentDescription} +values, or both.
+ +The {@code uiautomatorviewer} tool provides a convenient visual interface to inspect the layout +hierarchy and view the properties of UI components that are visible on the foreground of the device. +This information lets you create more fine-grained tests using UI Automator. For example, you can +create a UI selector that matches a specific visible property.
+ +To launch the {@code uiautomatorviewer} tool:
+ +$ uiautomatorviewer+
To view the UI properties for your application:
+ +To learn about the common types of UI components provided by Android, see +User Interface.
+ +The UI Automator test framework depends on the accessibility features of the Android framework +to look up individual UI elements. As a developer, you should implement these minimum +optimizations in your {@link android.app.Activity} to support UI Automator:
+ +Generally, app developers get accessibility support for free, courtesy of +the {@link android.view.View} and {@link android.view.ViewGroup} +classes. However, some apps use custom view elements to provide a richer user experience. Such +custom elements won't get the accessibility support that is provided by the standard Android UI +elements. If this applies to your app, make sure that it exposes the custom-drawn UI element to +Android accessibility services by implementing the +{@link android.view.accessibility.AccessibilityNodeProvider} class.
+ +If the custom view element contains a single element, make it accessible by +implementing +accessibility API methods. +If the custom view contains elements that are not views themselves (for example, a +{@link android.webkit.WebView}, make sure it implements the +{@link android.view.accessibility.AccessibilityNodeProvider} class. For container views that +extend an existing container implementation +(for example, a {@link android.widget.ListView}), implementing +{@link android.view.accessibility.AccessibilityNodeProvider} is not necessary.
+ +For more information about implementing and testing accessibility, see +Making Applications Accessible.
+ +To build a UI Automator test, create a class that extends +{@link android.test.InstrumentationTestCase}. Implement the following programming model in your +UI Automator test class:
+ +These steps are covered in more detail in the sections below.
+ +The +{@code UiDevice} + object is the primary way you access and manipulate the state of the +device. In your tests, you can call +{@code UiDevice} +methods to check for the state of various properties, such as current orientation or display size. +Your test can use the +{@code UiDevice} +object to perform device-level actions, such as forcing the device into a specific rotation, +pressing D-pad hardware buttons, and pressing the Home and Menu buttons.
+ +It’s good practice to start your test from the Home screen of the device. From the Home screen +(or some other starting location you’ve chosen in the device), you can call the methods provided by +the UI Automator API to select and interact with specific UI elements.
+ +The following code snippet shows how your test might get an instance of +{@code UiDevice} +and simulate a Home button press:
+ +
+import android.test.InstrumentationTestCase;
+import android.support.test.uiautomator.UiDevice;
+import android.support.test.uiautomator.By;
+
+public class CalculatorUiTest extends InstrumentationTestCase {
+
+ private UiDevice mDevice;
+
+ public void setUp() {
+ // Initialize UiDevice instance
+ mDevice = UiDevice.getInstance(getInstrumentation());
+
+ // Start from the home screen
+ mDevice.pressHome();
+ mDevice.wait(Until.hasObject(By.pkg(getHomeScreenPackage()).depth(0)),
+ }
+}
+
+
+Use the +{@code findObject()} +method to retrieve a +{@code UiObject} +which represents a view that matches a given selector criteria. You can reuse the +{@code UiObject} +instances that you have created in other parts of your app testing, as needed. Note that the +UI Automator test framework searches the current display for a match every time your test uses a +{@code UiObject} +instance to click on a UI element or query a property.
+ +The following snippet shows how your test might construct +{@code UiObject} +instances that represent a Cancel button and a OK button in an app.
+ +
+UiObject cancelButton = mDevice.findObject(new UiSelector()
+ .text("Cancel"))
+ .className("android.widget.Button"));
+UiObject okButton = mDevice.findObject(new UiSelector()
+ .text("OK"))
+ .className("android.widget.Button"));
+
+// Simulate a user-click on the OK button, if found.
+if(okButton.exists() && okButton.isEnabled()) {
+ okButton.click();
+}
+
+
+If you want to access a specific UI component in an app, use the +{@code UiSelector} +class. This class represents a query for specific elements in the +currently displayed UI.
+ +If more than one matching element is found, the first matching element in the layout hierarchy +is returned as the target +{@code UiObject}. +When constructing a +{@code UiSelector}, +you can chain together multiple properties to refine your search. If no matching UI element is +found, a + +{@code UiAutomatorObjectNotFoundException} is thrown.
+ +You can use the +{@code childSelector()} +method to nest multiple +{@code UiSelector} +instances. For example, the following code example shows how your test might specify a search to +find the first {@link android.widget.ListView} in the currently displayed UI, then search within that +{@link android.widget.ListView} to find a UI element with the text property Apps.
+ +
+UiObject appItem = new UiObject(new UiSelector()
+ .className("android.widget.ListView")
+ .instance(1)
+ .childSelector(new UiSelector()
+ .text("Apps")));
+
+
+As a best practice, when specifying a selector, you should use a Resource ID (if one is assigned +to a UI element) instead of a text element or content-descriptor. Not all elements have a text +element (for example, icons in a toolbar). Text selectors are brittle and can lead to test failures +if there are minor changes to the UI. They may also not scale across different languages; your text +selectors may not match translated strings.
+ +It can be useful to specify the object state in your selector criteria. For example, if you want +to select a list of all checked elements so that you can uncheck them, call the + +{@code checked()} +method with the argument set to {@code true}.
+ +Once your test has obtained a +{@code UiObject} +object, you can call the methods in the +{@code UiObject} +class to perform user interactions on the UI component represented by that +object. You can specify such actions as:
+ +The UI Automator testing framework allows you to send an +{@link android.content.Intent} +or launch an {@link android.app.Activity} +without using shell commands, by getting a +{@link android.content.Context} +object through +{@link android.app.Instrumentation#getContext() getContext()}.
+ +The following snippet shows how your test can use an +{@link android.content.Intent} to launch the app under test. This approach is useful when you are +only interested in testing the calculator app, and don't care about the launcher.
+ +
+public void setUp() {
+ ...
+
+ // Launch a simple calculator app
+ Context context = getInstrumentation().getContext();
+ Intent intent = context.getPackageManager()
+ .getLaunchIntentForPackage(CALC_PACKAGE);
+ intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
+ // Clear out any previous instances
+ context.startActivity(intent);
+ mDevice.wait(Until.hasObject(By.pkg(CALC_PACKAGE).depth(0)), TIMEOUT);
+}
+
+
+Use the + + {@code UiCollection} +class if you want to simulate user interactions on a +collection of items (for example, songs in a music album or a list of emails in an Inbox). To +create a + + {@code UiCollection} +object, specify a +{@code UiSelector} +that searches for a +UI container or a wrapper of other child UI elements, such as a layout view that contains child UI +elements.
+ +The following code snippet shows how your test might construct a + + {@code UiCollection} +to represent a video album that is displayed within a {@link android.widget.FrameLayout}:
+ +
+UiCollection videos = new UiCollection(new UiSelector()
+ .className("android.widget.FrameLayout"));
+
+// Retrieve the number of videos in this collection:
+int count = videos.getChildCount(new UiSelector()
+ .className("android.widget.LinearLayout"));
+
+// Find a specific video and simulate a user-click on it
+UiObject video = videos.getChildByText(new UiSelector()
+ .className("android.widget.LinearLayout"), "Cute Baby Laughing");
+video.click();
+
+// Simulate selecting a checkbox that is associated with the video
+UiObject checkBox = video.getChild(new UiSelector()
+ .className("android.widget.Checkbox"));
+if(!checkBox.isSelected()) checkbox.click();
+
+
+Use the + + {@code UiScrollable} +class to simulate vertical or horizontal scrolling across a display. This technique is helpful when +a UI element is positioned off-screen and you need to scroll to bring it into view.
+ +The following code snippet shows how to simulate scrolling down the Settings menu and clicking +on an About tablet option:
+ +
+UiScrollable settingsItem = new UiScrollable(new UiSelector()
+ .className("android.widget.ListView"));
+UiObject about = settingsItem.getChildByText(new UiSelector()
+ .className("android.widget.LinearLayout"), "About tablet");
+about.click();
+
+
+The {@link android.test.InstrumentationTestCase} extends {@link junit.framework.TestCase}, so +you can use standard JUnit {@code Assert} methods to test +that UI components in the app return the expected results.
+ +The following snippet shows how your test can locate several buttons in a calculator app, click +on them in order, then verify that the correct result is displayed.
+ +
+private static final String CALC_PACKAGE = "com.myexample.calc";
+
+public void testTwoPlusThreeEqualsFive() {
+ // Enter an equation: 2 + 3 = ?
+ mDevice.findObject(new UiSelector()
+ .packageName(CALC_PACKAGE).resourceId("two")).click();
+ mDevice.findObject(new UiSelector()
+ .packageName(CALC_PACKAGE).resourceId("plus")).click();
+ mDevice.findObject(new UiSelector()
+ .packageName(CALC_PACKAGE).resourceId("three")).click();
+ mDevice.findObject(new UiSelector()
+ .packageName(CALC_PACKAGE).resourceId("equals")).click();
+
+ // Verify the result = 5
+ UiObject result = mDevice.findObject(By.res(CALC_PACKAGE, "result"));
+ assertEquals("5", result.getText());
+}
+
+
+UI Automator tests are based on the {@link android.app.Instrumentation} class. The + + Android Plug-in for Gradle +provides a default directory ({@code src/androidTest/java}) for you to store the instrumented test +classes and test suites that you want to run on a device. The plug-in compiles the test +code in that directory and then executes the test app using a test runner class. You are +strongly encouraged to use the +{@code AndroidJUnitRunner} +class provided in the +Android Testing Support Library +as your default test runner.
+ +To run UI Automator tests in your Gradle project:
+ +
+android {
+ defaultConfig {
+ testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
+ }
+}
+./gradlew cC+