Transferred from: http://blog.chengyunfeng.com/?p=504
When Android 4.1 was released, it included a new test tool, –uiautomator,uiautomator, for UI testing. This is the normal manual test, click on each control element to see if the output is as expected. For example, the login interface to enter the correct and incorrect user name password and then click the Login button to see if it can login and whether there are errors and so on.
Functional or black-box UI tests do not require testers to understand how the program is implemented, only to verify that the results of the various operations meet expectations. Such tests can isolate the team's developers and testers. We do not have too many intersections.
The usual way of UI testing is manual verification, that is, the tester with a variety of mobile phones to install the program to test and then see if they can correctly complete the various scheduled functions. However, this verification method is very time-consuming, each time the return to the full verification side, and also prone to human error. A more efficient and reliable way to test your UI is to automate Tests. Automated UI tests Create test code to perform test tasks, and various test tasks cover different usage scenarios, and then use the test framework to run these test tasks.
Uiautomator is your automated UI testing tool.
Overview
The Android SDK provides the following tools to support UI Automation testing in 4.1:
- uiautomatorviewer– a graphical interface tool to scan and analyze your app's UI controls.
- uiautomator– A test Java library that contains the various APIs for creating UI tests and the engine that performs the automated tests.
To use the tool, the following conditions are required:
- Android SDK Tools, Revision or higher
- Android SDK Platform, API, or higher
Uiautomator Workflow for testing tools
Here is an overview of the Uiautomator workflow process:
- Install the apps you want to test into your phone, analyze the UI elements of your app, and make sure that the controls that are being tested are available to the test tools.
- Create known test cases to simulate user action steps in your app.
- Compile the test case code for the jar package and copy the jar package to the test phone on which the application is being tested.
- Run Tests and view results
- Modify any bugs that are found, and then repair and re-test.
Analyze UI elements for the application under test
Before you begin writing your test case code, you need to familiarize yourself with the UI elements of the app you're testing. The Uiautomatorviewer tool can be used to obtain an application's interface and analyze it. The Uiautomatorviewer tool provides a convenient way to view the UI layout structure and to view the related properties of individual controls. This information can be used to create UI test code.
Uiautomatorviewer Tools
The steps to analyze the application UI interface for testing are as follows:
1. Connect the Android phone to the computer
2. Open a command-line window and navigate to the directory/tools/
Run the following command: $ uiautomatorviewer
Run the Uiautomatorviewer.bat command under Windows
3. Click the "Device screenshot" button next to the folder button in the upper right corner of the Uiautomatorviewer tool to get the current screen interface information.
Note: If the current computer is connected to more than one device, specify the device to be analyzed by setting the android_serial environment variable. The steps are as follows:
A. Run the following command to get the serial number of the device connected to your computer
$ ADB devices
B. Set android_serial to the device serial number that needs to be tested
Windows:set android_serial=
Unix:export android_serial=
If your computer is connected to only one device, you do not need to set the android_serial environment variable.
4. Look at the UI element properties of the survey application
Place the mouse over the control on the left side of the Uiautomatorviewer tool to view the properties of the control. The properties are displayed below the right side of the screen, with the layout structure of the current interface displayed.
Click the yellow triangle button (Toggle NAF Nodes) at the top right to see the controls that cannot be accessed by the Uiautomator test tool. These controls set only a limited number of properties, so uiautomator cannot get to these controls. So you might have a hard time testing these controls. In this case you can ask the developer to add the necessary properties for these controls, such as ImageView or ImageButton should add the Android:contentdescription attribute.
Test prep Work
Before you start using uiautomator, you need to complete the following preparations:
Install the application to be tested on the test phone (device)
When you're ready to test, the app you're testing may not have been released to the market. However, you should have the APK installation file for the app, you can install the app to be tested on the phone via the ADB tool, or install the APK via other tools.
Identify app UI controls for testing
Before you start writing Uiautomator test code, you need to identify the UI control elements of the app you're testing. In general, the UI elements of an excellent application for testing should be visible and user-accessible. These UI elements should also have visible text labels, android:contentdescription values, or two.
The Uiautomatorviewer tool lets you view the visible controls for your app. Specific usage is described above.
Ensure that the application under test is accessible
This is not very important because the Uiautomator tool relies on the accessible lines of the Android device to get the UI controls. To support the Uiautomator tool, you need a condition:
- Use the Android:contentdescription property to set the label for ImageButton, ImageView, checkbox, and other controls.
- Use the Android:hint property to mark the EditText control instead of using the text inside it (the text content user can modify).
- For the UI (text or icon) used to provide visual feedback of the operation, a Android:hint attribute is added to identify it.
- Ensure that all user-accessible interface elements can be selected (such as trackball) through the direction control key.
- Use the Uiautomatorviewer tool to ensure that all UI elements can be accessed by the test tool. You can also test the accessibility of the UI through services such as "TalkBack" in accessibility (in the Setup interface).
Setting up the development environment
If you are using Eclipse (ADT), the Android SDK provides additional tools to help you write Uiautomator test code and package your test project. The process for creating a Uiautomator test project in Eclipse is as follows:
- Create a new Java project (note that it is not an Android project). In the project, create the test code.
- In the Project Explorer view, right-click the test project, select Properties > Java Build Path, and select the Libraries tab interface. In the "Libraries" screen, select "Add Library > JUnit" to add the JUNIT3 library. Then click "Add External JARs ... "and navigate to the Android SDK directory. Select the Uiautomator.jar and Android.jar files under the platforms directory.
- Set the build path as:
Uiautomator Project Classpath Settings
If you do not use eclipse, you need to make sure that the Uiautomator.jar and Android.jar in the/platforms/directory are in project build path.
Once you've configured your development environment, you're ready to start writing your test code.
Create a Uiautomator test case
The Uiautomator test case needs to be inherited to the Uiautomatortestcase class. The Uiautomatortestcase class inherits from the Junit.framework.TestCase class, so you can compare the test results with the JUnit assert class.
The first task of the UI test is to access the test phone. Usually from the phone's main screen to start testing. The API provided by Uiautomator can be used to simulate a user's actions from the main screen. Specific examples are described below.
Uiautomator API
The Uiautomator API is in the Uiautomator.jar file. These APIs are as follows:
Uidevice
Represents the device status. In the test, you can use Uidevice instances to detect various properties of the device, such as the current screen orientation and screen size. You can also perform device-level operations with Uidevice instances, such as setting the device to a horizontal or vertical screen, pressing the home button, and so on.
Here is the code that simulates pressing the home button:
Getuidevice (). Presshome ();
Uiselector
Represents a condition for a search UI control. If more than one control that satisfies a condition is found, the first control is returned. The returned result is a UIObject object. When constructing uiselector, you can combine multiple properties to locate a specific control. If no control is found, the uiautomatorobjectnotfoundexception exception is thrown. You can also use the Childselector () function to nest Uiselector objects. For example, the following code shows how to find a child control in the first ListView with the Text property of apps in the current interface.
UiObject Appitem = new UiObject (new Uiselector (). ClassName ("Android.widget.ListView"). Instance (1). Childselector (New Uiselector (). Text ("Apps"));
UiObject
Represents a UI control. Find UIObject through Uiselector.
The following example code shows how to find the Cancel button and the Confirm button in the current display interface:
UiObject CancelButton = new UiObject (new Uiselector (). Text ("Cancel")); UiObject OKButton = new UiObject (new Uiselector (). Text ("OK");
The UIObject instances found can be reused in other test code. Note that every time you use UIObject to do this, Uiautomator will look for the control again on the current screen.
The following code uiautomator the tool to find the control with the text content as "OK" in the current interface. If present and available then impersonate the user to click on the control.
if (okbutton.exists () && okbutton.isenabled ()) {Okbutton.click ();}
You can also restrict the search to only specific types of controls. For example, the following code only looks for Android.widget.Button type controls with text "Cancel" and "OK".
UiObject CancelButton = new UiObject (new Uiselector (). Text ("Cancel"). ClassName ("Android.widget.Button")); UiObject OKButton = new UiObject (new Uiselector (). Text ("OK"). ClassName ("Android.widget.Button"));
Uicollection
Represents a collection of controls. Get uicollection in the same way as UIObject, through Uiselector lookups. The uicollection corresponds to the ViewGroup and child controls in the Android system.
The following code shows how to get the uicollection that contains the video collection through Uiselector.
Uicollection videos = new Uicollection (new Uiselector (). ClassName ("Android.widget.FrameLayout"));
If each video is placed in the LinearLayout, you can get the number of videos as follows:
int count = Videos.getchildcount (new Uiselector (). ClassName ("Android.widget.LinearLayout"));
If you need to find a video labeled "Cute Baby Laughing" and click on it. This can be done in the following ways:
UiObject video = Videos.getchildbytext (new Uiselector () className ("Android.widget.LinearLayout"), "Cute Baby laughing "); Video.click ();
You can also simulate other user actions. For example, the analog selection video operation is as follows:
UiObject CheckBox = video.getchild (new Uiselector (). ClassName ("Android.widget.Checkbox")); if (!checkbox.isselected ( )) Checkbox.click ();
Uiscrollable
Represents a scrollable control. You can use uiscrollable to simulate a horizontal or vertical scrolling UI element. You need to use uiscrollable if the element you want to manipulate needs to scroll the screen outside the screen to see it.
For example, the following code shows how to simulate scrolling to the "Settings" menu and clicking on the "About tablet" menu.
Uiscrollable Settingsitem = new Uiscrollable (new Uiselector (). ClassName ("Android.widget.ListView")); UiObject about = Settingsitem.getchildbytext (new Uiselector (). ClassName ("Android.widget.LinearLayout"), "about Tablet "); About.click ()
Other API reference Uiautomator API documentation.
A simple uiautomator test case
Here is a simple test case code that simulates the Click home button to go back to the main screen, then click on the Apply buttons to open all apps list and scroll to the clock app. Turn on the clock app and select the first alarm setting in the alarm interface to modify the setting's switch. Then go back to the clock interface and then into the Countdown screen.
Package Com.uia.example.my;import Android.widget.listview;import Android.widget.switch;import Com.android.uiautomator.core.uiobject;import Com.android.uiautomator.core.uiobjectnotfoundexception;import Com.android.uiautomator.core.uiscrollable;import Com.android.uiautomator.core.uiselector;import Com.android.uiautomator.testrunner.uiautomatortestcase;public class Launchsettings extends UiAutomatorTestCase {// TODO Important NOTE: When you run the test code, you need to set the language environment of your phone to English first. public void Testdemo () throws Uiobjectnotfoundexception {//Analog HOME key Click event Getuidevice (). Presshome (); Now that the main screen app is open, simulate clicking on All App button actions to launch all of the app interfaces. If you use Uiautomatorviewer to view the home screen, you can see that the//Content-description property of the All Apps button is "apps." You can use this property to find the button. UiObject Allappsbutton = new UiObject (new Uiselector (). Description ("Apps")); Analog Click All Apps button and wait for all app interface up Allappsbutton.clickandwaitfornewwindow (); In all application interfaces, the clock app is located in the Apps tab interface. The following simulates the user clicking on the Apps tab action. Find Apps tab button UiObject Appstab =New UiObject (New Uiselector (). Text ("Apps"); Simulate clicking on Apps tab. Appstab.click (); Then in the Apps tab interface, simulate the user sliding to the clock app's operation. Since the apps interface can be scrolled, all with//uiscrollable objects. Uiscrollable appviews = new Uiscrollable (new Uiselector (). Scrollable (true)); Sets the scrolling mode to horizontal scrolling (default to vertical scrolling) appviews.setashorizontallist (); if (allappsbutton.exists () && allappsbutton.isenabled ()) {//Allappsbutton is not visible in the current interface so this will not be performed Allappsbutton.click (); }//Find the Clock app and click UiObject settingsapp = Appviews.getchildbytext (new Uiselector (). ClassName (and Roid.widget.TextView.class.getName ()), "Clock"); Settingsapp.clickandwaitfornewwindow (); Verify that the currently displayed app package name is clock UiObject settingsvalidation = new UiObject (new Uiselector (). PackageName ("Com.google.android.desk Clock ")); If it does not exist then the error prompt asserttrue ("Unable to detect Clock", settingsvalidation.exists ()); Analog Click time tab UiObject clocK = new UiObject (new Uiselector (). Description ("Clock")); Clock.clickandwaitfornewwindow (); Analog Click on the alarm icon below UiObject alarms = new UiObject (new Uiselector (). Description ("alarms")); Alarms.clickandwaitfornewwindow (); Uiscrollable list = new Uiscrollable (new Uiselector (). ClassName (ListView.class.getName ())); if (List.getchildcount () > 0) {UiObject listIndex0 = list.getchild (new Uiselector (). Index (0)); UiObject switchbtn = listindex0.getchild (new Uiselector (). ClassName (Switch.class.getName ())); Boolean isChecked = switchbtn.ischecked (); Switchbtn.click (); }//Analog Click Back Key Getuidevice (). Pressback (); UiObject timer = new UiObject (new Uiselector (). Description ("timer")); Timer.clickandwaitfornewwindow (); }}
Package the test code and run it on the test machine
The following steps package the test code and run it on the test machine:
1. Create a build script that packs the test code. Generate a build script with the following command:
<android-sdk>/tools/android Create uitest-project-n <name> t 1-p <path>
<name> is the project name that contains the test code,<path> is the project file path that contains the test code. The 1 after-T is the Android SDK version ID.
Note: The test project has been created and the test code has been written before the build script is created. Only the test project does not contain a packaged script so it cannot be packaged and run. When creating the build script, the,<name> property is the name of the test project, <path> is the path to the folder in the computer where the test project has been created. If you have more than one version of the Android SDK installed on your computer, you will need to run /tools/android list target to see the ID of each SDK. Select more than 4.1 of the ID.
2. Set the ANDROID_HOME environment variable.
Windows:set android_home=
Unix:export android_home=
3. Open the command line creation, navigate to the directory in the first step, and run the ant build to package.
4. Use the ADB push command to copy the jar files packaged in the previous step to the test phone.
ADB push <path>/bin/<name>.jar/data/local/tmp/
Similar to the following code:
ADB push ~/dev/workspace/launchsettings/bin/launchsettings.jar/data/local/tmp/
Run the Uiautomator testhere is the command to run the test code in the Launchsettings.jar jar package. The test code is in the com.uia.example.my package.
adb shell Uiautomator runtest launchsettings.jar-c com.uia.example.my.LaunchSettings
For more information about Uiautomator, refer here: http://developer.android.com/tools/help/uiautomator/index.html
Best practices
Here are some best practices for using Uiautomator to do UI testing
- Run Uiautomator tests on as many devices as possible to run on the application under test. For example, run tests on different screen densities and different screen sizes.
- You should also test your UI in some general scenarios, such as phone entry, network disconnection, and so on.
Read MORE:HTTP://BLOG.CHENGYUNFENG.COM/?P=504#IXZZ3FZAHDSDD
Use Uiautomator to do UI testing