Android Test (vii): Espresso Automated Testing

Source: Internet
Author: User

Android Test (vii): Espresso Automated Testing

Release date December 20, 2017 bug Master

Original: https://developer.android.com/training/testing/ui-testing/espresso-testing.html

Testing user interaction in a single application helps ensure that users do not experience unexpected results when interacting with the application, or experience bad experiences. If you need to verify that your app's UI functionality is working, you should develop the habit of creating user interface (UI) tests.

The Espresso test framework, provided by the Android test Support library, is an API for writing UI tests to simulate user interaction within a single application. The espresso test can run on devices running Android 2.3.3 (API level 10) and later. A key benefit of using espresso is that it provides automatic synchronization of test operations with the user interface of the application being tested. Espresso detects if the main thread is idle so that test commands can be run at the appropriate time, thus improving the reliability of the test. This feature can also alleviate the hassle of adding any timing workarounds in your test code Thread.sleep() .

The espresso test framework is based on the instrumentation API and runs the tests through Androidjunitrunner.

Set Espresso

Before you build your UI tests using espresso, be sure to configure the test source code location and project dependencies, as described in "Getting Started with testing".

In the Build.gradle file of the Android application module, you must set up a dependency reference to the Espresso library:

// Other dependencies ...    androidTestCompile ‘com.android.support.test.espresso:espresso-core:2.2.2‘}

Turn off animation on a test device-opening a system animation in a test device can cause unexpected results or may cause the test to fail. Turn off the animation in settings by opening the developer option and turn off all of the following options:

    • Window Animation scale

    • Transition Animation Scale

    • Animator Duration ratio

If you want to set up your project to use features other than the espresso feature provided by the core API, see this resource

Create a espresso test

To create a espresso test, create a Java class that follows this programming model:

1. Locate the UI component that you want to test in the activity (for example, the login button in the application), call the Onview () method, or call the OnData () method of the Adapterview control.

2. Impersonate a specific user interaction to execute on the UI component by invoking the Viewinteraction.perform () or Datainteraction.perform () method and passing in the user action (for example, clicking the login button). To sort multiple operations on the same UI component, use the comma-separated list in the method parameter to link them.

3. Repeat the above steps as needed to simulate user actions for multiple activities in the target app.

4. After performing these user interactions, use the ViewAssertions method to check whether the UI reflects the expected state or behavior.

These steps are described in detail in the following sections.

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
Using Espresso and Activitytestrule

The following sections describe how to use the JUnit 4 style to create a new espresso test and use activitytestrule to reduce the number of boilerplate code that needs to be written. By using Activitytestrule, the test framework initiates the @Test activity before each test method that uses annotations and @Before before the method using annotations. When the test is complete, the framework handles the shutdown activity, and all @After methods that use annotations run.

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 Android.support.test.rule.ActivityTestRule;Import Android.support.test.runner.AndroidJUnit4, .....@RunWith (Androidjunit4.class)@LargeTestPublicClasschangetextbehaviortest {Private String mstringtobetyped;@RulePublic activitytestrule<mainactivity> Mactivityrule =New Activitytestrule<> (Mainactivity.class);@BeforePublicvoidInitvalidstring() {Specify a valid string. mstringtobetyped ="Espresso"; } @Test public void changetext_sameactivity() { //Type text and then press the Butto         N. Onview (Withid (R.id.edittextuserinput)). Perform (TypeText (mstringtobetyped), Closesoftkeyboard ());        Onview (Withid (R.ID.CHANGETEXTBT)). Perform (click ());        //Check that the text is changed.    Onview (Withid (r.id.texttobechanged)). Check (Matches (Withtext (mstringtobetyped))); }}
Accessing UI Builds

Before espresso can interact with the application being tested, you must first specify the UI component or view. Espresso supports specifying views and adapters in the application using the Hamcrest match.

To find a view, call the onView() method and pass a view match that specifies the view to locate. This is described in more detail in the specified view-matching device. onView()method returns ViewInteraction an object that allows the test to interact with the view. However, if you are looking for a view in a RecyclerView layout, the calling onView() method may not work. In this case, follow the instructions in Find a view in Adapterview.

Note: the Onview () method does not check whether the view you specified is valid. Instead, espresso only searches the current view hierarchy, using the view provided by Matcher. If no match is found, the method throws a nomatchingviewexception.

The following code snippet shows how to write a test to access the EditText field, enter a text string, close the virtual keyboard, and then perform 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.    ...}
Specify a view-matching device

You can specify a view match by using the following methods:

    • The method is called in the Viewmatchers class. For example, to find the displayed text string to find the view, you can call a method such as the following:
onView(withText("Sign-in"));

You can also call Withid () and provide the resource ID (r.id) for the view, as shown in the following example:

onView(withId(R.id.button_signin));

The Android resource ID is not guaranteed to be unique. If the test tries to match the resource ID used by multiple views, espresso raises ambiguousviewmatcherexception.

    • Use the Hamcrest matchers class. You can use AllOf() methods to combine multiple matches, such as containsString() and instanceOf() . This approach allows you to filter the matching results more narrowly, as shown in the following example:
onView(allOf(withId(R.id.button_signin), withText("Sign-in")));

However, you cannot use a keyword to filter a view that does not match the match, as shown in the following example:

onView(allOf(withId(R.id.button_signin), not(withText("Sign-out"))));

To use these methods in your tests, import the org.hamcrest.Matchers package. To learn more about hamcrest matches, see the Hamcrest website

To improve the performance of the espresso test, specify the minimum matching information that is required to find the target view. For example, if a view can be uniquely identified by its descriptive text, you do not need to specify it or you can assign it from a TextView instance.

Find a view in Adapterview

In the Adapterview widget, the view dynamically fills the child view at run time. If the target view that you want to test is in Adapterview (such as Listview,gridview or spinner), the onView() method may not work correctly because only a subset of the view may be loaded into the current view hierarchy.

Instead, call the onData() method to get the Datainteraction object to access the target view element. Espresso loads the target view element into the current view hierarchy. The espresso is also responsible for scrolling the target element and placing the element in focus.

Note: the OnData () method does not check whether the item you specified corresponds to the view. Espresso searches only the current view hierarchy. If a match is not found, the method throws a nomatchingviewexception.

The following code snippet shows how to use onData() methods and Hamcrest matches to search for specific rows in a list that contains a given string. In this example, the Longlistactivity class contains a list of strings exposed through simpleadapter.

onData(allOf(is(instanceOf(Map.class)),        hasEntry(equalTo(LongListActivity.ROW_TEXT), is("test input")));
Perform actions

Call ViewInteraction.perform() or DataInteraction.perform() method to impersonate the user interaction on the UI component. You must pass in one or more Viewaction objects as parameters. Espresso triggers each action in the order given, and executes them in the main thread.

The Viewactions class provides a list of helper methods for specifying common operations. Instead of creating and configuring separate Viewaction objects, you can use these methods as handy shortcuts. You can specify the following actions:

    • Viewactions.click (): click View.

    • Viewactions.typetext (): Click on a view and enter a specified string.

    • Viewactions.scrollto (): Scroll to view. The target view must inherit from ScrollView, and the value of its Android:visibility property must be visible. For a view that extends Adapterview (for example, a ListView), the OnData () method is responsible for scrolling for you.

    • Viewactions.presskey (): keys are operated using the specified key.

    • Viewactions.cleartext (): Clears the text in the target view.

If the target view is inside the ScrollView, the action is performed before ViewActions.scrollTo() other actions are performed. If the view is already displayed, the ViewActions.scrollTo() operation will not work.

Test your activity with espresso intents isolation

Espresso intents can verify the authentication and stub of the intent sent by the application. By espresso Intents, you can isolate a test application, activity, or service by intercepting the outgoing intent, stub the result, and send it back to the tested component.

// Other dependencies ...  androidTestCompile ‘com.android.support.test.espresso:espresso-intents:2.2.2‘}

To test a intent, you need to create an instance of the Intentstestrule class that is very similar to the Activitytestrule class. The Intentstestrule class initializes the espresso Intents before each test, terminates the main activity, and releases espresso Intents after each test.

The test class shown in the following code snippet provides a simple test for explicit intent. It tests the activities and intentions created in building your first application tutorial.

@Large@RunWith (Androidjunit4.class)PublicClasssimpleintenttest {PrivateStaticFinal String MESSAGE ="This is a test";PrivateStaticFinal String package_name ="Com.example.myfirstapp";/* Instantiate an Intentstestrule object. */@RulePublic intentstestrule? Mainactivity> Mintentsrule =New Intentstestrule?> (Mainactivity.class);@TestPublicvoidVerifymessagesenttomessageactivity() {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 I ntent        //with the correct package name and message.    &NB Sp   Intended (AllOf (                hascomponent (hasshortclassname) ( 

For more information about Espresso intents, see the Espresso intent documentation on the Android Test Support library website. You can also download the intentsbasicsample and Intentsadvancedsample code samples.

Using Espresso Web Test webviews

The Espresso Web allows the WebView component contained in the test activity. It uses the Webdriver API to check and control the behavior of WebView.

To start testing with the espresso Web, you need to add the following line to the application's Build.gradle file:

// Other dependencies ...  androidTestCompile ‘com.android.support.test.espresso:espresso-web:2.2.2‘}

When you create a test using the espresso Web, you need to enable JavaScript on WebView when instantiating the Activitytestrule object to test the activity. In the test, you can select the HTML element that appears in WebView and simulate user interaction, such as entering text in a text box, and then clicking the button. After you complete the operation, you can verify that the results on the Web page match the expected results.

In the following code snippet, this class tests a WebView component with the ID value of the component "WebView" in the activity being tested. verifyValidInputYieldsSuccesfulSubmission()Test Select the elements on the Web page <input> , enter some text, and examine the text that appears in the other element.

@LargeTest@RunWith (Androidjunit4.class)PublicClasswebviewactivitytest {PrivateStaticFinal String macchiato ="Macchiato";PrivateStaticFinal String Doppio ="Doppio";@RulePublic Activitytestrule Mactivityrule =New Activitytestrule (Webviewactivity.class,False/* Initial Touch mode */,False/* Launch activity */) {@OverrideProtectedvoidAfteractivitylaunched() {Enable JavaScript.        Onwebview (). forcejavascriptenabled (); }    }@TestPublicvoidTypetextininput_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 the multiple webviews you can also use aMatcher 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. Witheleme           NT (Findelement (locator.id, "response")) //Verify that the response page contains the entered text    . Check (Webmatches (GetText (), containsstring (Macchiato))); }}

For more information about the espresso web, see the Espresso Web document on the Android Test Support library website. You can also download this snippet as part of the Espresso Web code sample.

Validation results

Call ViewInteraction.check() or DataInteraction.check() method to declare that the view in the UI matches an expected state. Must be passed to the Viewassertion object as a parameter. If the assertion fails, espresso throws a assertionfailederror.

The Viewassertions class provides a list of helper methods for specifying public assertions. The assertions you can use include:

    • Doesnotexist: Asserts that there are no views in the current view hierarchy that match the specified criteria.

    • Matches: asserts that the specified viewport survival in the current view hierarchy and whose state matches the given Hamcrest match.

    • Selecteddescendentsmatch: Declares that a child view of the specified parent view exists, and their state matches the given Hamcrest match.

The following code snippet shows how to check that the text displayed in the user interface has the same value as the text that was previously entered in the 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)));}
Run the espresso test on a device or emulator

You can run the espresso test from Android studio or from the command line. Make sure that Androidjunitrunner is specified as the default detection tool in the project.

To run the espresso test, follow the steps described in the previous section to run the tested test.

Android Test (vii): Espresso Automated Testing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.