Uiautomator Android website translation

Source: Internet
Author: User
Tags gettext home screen

http://www.jianshu.com/p/7718860ec657 2016.07.25 20:59 words 3675 Android Uiautomator Brief introduction of the--------------------------------------------------------------------------------Uiautomator is Google launched , a tool for UI Automation testing, i.e., a 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. Note: UI Automator test framework is instrumentation based API that runs on Android Junitrunner while UI Automator test only runs on Android 4.3 (API level 18) The above version. To prepare for integrated UI Automator, you first need to make sure that the app project already relies on gradle testing. Then add the following dependencies in the Gradle. dependencies {androidtestcompile ' com.android.support.test.uiautomator:uiautomator-v18:2.1.1 '} UI element lookup in Android development, Findviewbyid can be planted to find the appropriate control, but UI Automator is used to test the interface, and if it is in the same way, it will be very dependent. UI Automator uses a similar approach to finding elements. UI Automator is looked up based on the elements ' text, hint, contentdescription, and so on, in order for the UI Automator to get the above property values, the test UI interface is accessible, and the UI Automator can also access these control elements. You can use Uiautomatorviewer to get the hierarchical relationships of interface elements and the properties of individual elements, and then UI Automator to find the corresponding control elements based on these property information. Get steps: Launch the app on the device to connect the device to the development machine to open the Android SDK directory, <android-sdk>/tools/. Start Uiautomatorviewer and then you can operate Uiautomatorviewer click Device Screenshot, wait a minute, get a snapshot of the screen, the right side of the interface is the layout structure of the current interface and property information. Make sure the UI is accessible as described above, UI Automator is looked up based on the elements ' text, hint, contentdescription, and so on, so you need to add the above attributes to the elements in the layout whenever possible. Sometimes programmers need to customize some of the controls, so implement Accessibilitynodeprovider to make sure they are working. Access UI Control UI Automator provides a Uidevice class that provides methods to get some state and properties of a device while performing a series of actions to manipulate the device. Here is an example of how to get the Uidevice object and press the home key. Import Org.junit.before;import Android.support.test.runner.androidjunit4;import Android.support.test.uiautomator.uidevice;import Android.support.test.uiautomator.by;import Android.support.test.uiautomator.Until @RunWith (Androidjunit4.class) @SdkSuppress (minsdkversion =) public Class Changetextbehaviortest {private static final String basic_sample_package = "Com.example.android.testi    Ng.uiautomator.BasicSample ";    private static final int launch_timeout = 5000;    private static final String string_to_be_typed = "Uiautomator";    Private Uidevice Mdevice; @Before public void Startmainactivityfromhomescreen () {//Initialize Uidevice instance MDevice = Uidevice.getinstance (Instrumentationregistry.getinstrumentation ());        Start from the Home Screen Mdevice.presshome ();        Wait for launcher final String launcherpackage = Mdevice.getlauncherpackagename ();        Assertthat (Launcherpackage, Notnullvalue ());        Mdevice.wait (Until.hasobject (by.pkg (launcherpackage) Depth (0)), launch_timeout);        Launch the app Context context = Instrumentationregistry.getcontext ();        Final Intent Intent = Context.getpackagemanager (). Getlaunchintentforpackage (Basic_sample_package);        Clear out any previous instances intent.addflags (Intent.flag_activity_clear_task);        Context.startactivity (Intent); Wait for the app to appear mdevice.wait (Until.hasobject (by.pkg (basic_sample_package). Depth (0)), L    Aunch_timeout); You can then use the Findobject () method to get UI controls to the interface, as shown below, to find the UI elements that match the rules on a device, and then perform some column actions. 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.clic K ();} Specify a selector sometimes, you need access to a specific UI component, and you can use Uiselector. This class provides methods for columns to help find specific UI components. The first element is not used when there are multiple qualifying UI elements to be found. A uiselector-to-construct method that can be passed is equivalent to chained access. If no element is found, then an uiautomatorobjectnotfoundexception exception is thrown. You can also use Childselector () to select more than one Uiselector object, as shown below, many of the child elements of the ListView are the same, and depending on this method, a child element can be selected. UiObject Appitem = new UiObject (new Uiselector (). ClassName ("Android.widget.ListView"). Instance (1). Childselector (New Uiselector (). Text ("Apps")); The above lookup is still very complex, and we can replace the way text is found based on ResourceID. The way the text is found is fragile, and it makes the test fail, and when the language environment changes, text lookup needs to control multiple translated versions of text. Execute action when we find the corresponding text element based on the text lookup, we can do whatever we want. Click () dragto () Drag the current element SetText () to set the text Swipeup () to slide up, as well as down, left, right, Swipedown, Swipeleft, swiperight。 UI Automator can also provide a context so that it is easy to send a intent or start an activity.    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);} A collection operation can use Uicollection to impersonate a user to manipulate a set of UI controls, such as sometimes a ListView on the interface. In order to create a Uicollection object, you can specify a uiselector search for all child elements on this UI container that satisfy this condition. The following code shows how to operate in a group of controls. Uicollection videos = new Uicollection (new Uiselector () className ("Android.widget.FrameLayout"));//Retrieve The N Umber of videos in this collection:int count = Videos.getchildcount (new Uiselector (). ClassName ("Android.widget.Lin Earlayout "));//Find a specific video and simulate a user-click on ituiobject video = Videos.getchildbytext (New Uiselector (). ClAssname ("Android.widget.LinearLayout"), "Cute Baby Laughing"); Video.click ();//Simulate selecting a checkbox that's Associated with the Videouiobject CheckBox = Video.getchild (new Uiselector (). ClassName ("Android.widget.Checkbox")) , if (!checkbox.isselected ()) Checkbox.click (), the action can be scrolled UI elements can use the uiscrollable to simulate the user's interface scrolling operation (horizontal, vertical), this technology can help us to take care of, When an interface is not displayed, we can scroll the interface and display the interface. Uiscrollable Settingsitem = new Uiscrollable (new Uiselector (). ClassName ("Android.widget.ListView")); UiObject about = Settingsitem.getchildbytext (new Uiselector (). ClassName ("Android.widget.LinearLayout"), "about tab About.click (); The checksum result UI Automator is based on Instrumentationtestcase, and the same instrumentationtestcase is a standard-based JUnit Assert, Then we can also use the standard JUnit assert to determine the result. The following code snippet shows the code for a calculator, along with the validation results. private static final String calc_package = "Com.myexample.calc";p ublic 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 ());} Apiuidevicevoid Clearlasttraversedtext ()//clears the text from the last UI traversal event.//clear the previous UI traversal event? Boolean click (int x, int y)//Perform a click at arbitrary coordinates specified by the user//click on the Boolean drag (in T StartX, int starty, int endx, int endY, int steps)//performs a swipe from one coordinate to another coordinate.//drag Voi d dumpwindowhierarchy (file dest)//Dump the current window hierarchy to a file.//dump present hierarchical structure to file void Dumpwindowhie Rarchy (OutputStream out)//Dump the current winDow hierarchy to outputstream.//dump current hierarchical structure to stream void Dumpwindowhierarchy (String fileName)//This method is deprecate D. Use Dumpwindowhierarchy (file) or Dumpwindowhierarchy (outputstream) instead.//dump the current hierarchical structure into a file UiObject2 Findobject (byselector selector)//Returns the first object to match the selector criteria.//find Byselector UIObject based on Findobject (Ui Selector Selector)//Returns a UiObject which represents a view that matches the specified Selector criteria.//according to Uiselect or find list<uiobject2> findobjects (byselector selector)//Returns all objects that match the selector criteria.//root According to byselector find void freezerotation ()//disables the sensors and freezes the device rotation at it current rotation state .//freezes the rotated state of string getcurrentactivityname ()//This method is deprecated. The results returned should be considered unreliable//gets the name of the current activity, has been discarded string getcurrentpackagename ()//retrieves The name of the last accessibility events.//gets the current PackagEint getdisplayheight ()//Gets The height of the display, in Pixels.int getdisplayrotation ()//Returns the current R Otation of the display, as defined in Surfacepoint GETDISPLAYSIZEDP ()//Returns The display size in DP (device-independ ENT pixel) The returned display size is adjusted per screen rotation.int getdisplaywidth ()//Gets the width of the disp Lay, in Pixels.static uidevice getinstance ()//This method is deprecated. should use getinstance (instrumentation) instead. This version hides Uidevice's dependency on have a instrumentation reference and is prone to misuse.//gets an object static UiD Evice getinstance (instrumentation instrumentation)//retrieves a singleton instance of Uidevicestring Getlasttravers Edtext ()//retrieves the text from the last UI traversal event received.//Gets the previous traversed literal string getlauncherpackagename ()// Retrieves default launcher package name//get run packagenamestring getproductname ()//retrieves the product name of the D Evice.boolean hasAnywatchertriggered ()//Checks If any registered Uiwatcher has triggered.//check if there is a trigger to trigger a Boolean hasobject (Byselector sel Ector)//Returns whether there is a match for the given selector criteria.//if there are conditions that match the Boolean haswatchertriggered (Strin G watchername)//Checks if a specific registered Uiwatcher has Triggered.boolean isnaturalorientation ()//Check if the Device is in its natural Orientation.boolean isscreenon ()//Checks The Power Manager if the screen is On.boolean ope Nnotification ()//Opens the Notification shade.//Open Notification Boolean openquicksettings ()//Opens the Quick Settings shade.//hit Open Settings <R> R performactionandwait (Runnable action, eventcondition<r> condition, long Timeout)//performs the PR ovided action and waits for the condition to be Met.boolean pressback ()//simulates a short press on the back Button.bo Olean Pressdpadcenter ()//simulates a short press on the CENTER Button.boolean Pressdpaddown ()//simulates a short p Ress on the button.Boolean pressdpadleft ()//simulates a short press on the left Button.boolean pressdpadright ()//simulates a short PR ESS on the right Button.boolean Pressdpadup ()//simulates a short press on the Up Button.boolean pressdelete ()//Sim Ulates a short presses on the DELETE Key.boolean pressenter ()//simulates a short press on the ENTER Key.boolean  Home ()//simulates a short press on the HOME button.boolean presskeycode (int keycode)//simulates a short press using a Key Code.boolean presskeycode (int keycode, int metaState)//simulates a short press using a key Code.boolean PRESSM ENU ()//simulates a short press on the MENU Button.boolean Pressrecentapps ()//simulates a short press on the recent Ap PS Button.boolean Presssearch ()//simulates a short press on the SEARCH button.void registerwatcher (String name, UIW Atcher watcher)//registers a uiwatcher to run automatically when the testing framework was unable to find a match using a Uiselector.void RemovEwatcher (String name)//Removes a previously registered uiwatcher.void resetwatchertriggers ()//resets a UiWatcher that has been triggered.void runwatchers ()//This method forces all registered watchers to Run.void Setcompressedlayouth Eirarchy (Boolean compressed)//Enables or disables layout hierarchy compression.void Setorientationleft ()//simulates O Rienting the device to the left and also freezes rotation by disabling the sensors.//sets the direction of rotation void setorientationnatural (    )//simulates orienting the device into its natural orientation and also freezes rotation by disabling the sensors.void Setorientationright ()//simulates orienting the device to the right and also freezes rotation by disabling the SENSORS.VO ID sleep ()//This method simply presses the power button if the screens is on the other it does nothing if the that is Alre Ady off.//off Screen boolean swipe (int startX, int starty, int endx, int endY, int steps)//performs a swipe from one Coordin Ate to another using the Number of steps to determine smoothness and speed.boolean swipe (point[] segments, int segmentsteps)//performs a swipe  Between points in the "point Array.boolean takescreenshot" (File Storepath, float scale, int quality)//Take a screenshot of current window and store it as PNG the screenshot are adjusted per screen rotation//screenshot Boolean takescreenshot (File s Torepath)//Take a screenshot of the current window and the store it as PNG Default scale of 1.0f (original size) and 90% quality is used the screenshot are adjusted per screen rotationvoid unfreezerotation ()//re-enables the sensors and un-freezes t He device rotation allowing its contents-rotate with the device physical rotation.<r> R Wait (searchcondition&l T  r> condition, long Timeout)//Waits for given the condition to be met.void waitforidle (long Timeout)//Waits for the Current application to Idle.void Waitforidle ()//Waits for the current application to Idle.boolean WAITFORWINDOWUPD Ate (String PackageName, long Timeout)//Waits for a window content update event to occur.void wakeUp ()//This method simulates pressing the P Ower button if the screen was OFF else it does nothing if the screens is already on.//light up the display uiobjectvoid Cleartextfield ()/ /Clears the existing text contents in an editable field.//empty input interface Boolean click ()//performs a click at the center of T He visible bounds of the UI element represented by this uiobject.//click on the Boolean Clickandwaitfornewwindow ()//Waits for WI Ndow transitions that would typically take longer than the usual default timeouts.//click and wait for the new interface Boolean clickandwaitfornew  Window (long Timeout)//performs a click at the center of the visible bounds of the UI element represented by this UiObject and waits for window transitions.//Click and wait for the new interface, set the wait Time Boolean clickbottomright ()//Clicks the bottom and right corner of The UI element//Click on the bottom right of the Boolean clicktopleft ()//Clicks the top and left corner of the UI Elementboolean Dragto (Uiobje CT destobj, int steps)// Drags this object to a destination uiobject.//drag boolean dragto (int destx, int desty, int steps)//drags this object T o arbitrary coordinates.boolean exists ()//Check if view exists.//determine if there is a rect getbounds ()//Returns The view ' s bound s property.//return to Border UiObject Getchild (uiselector selector)//Creates a new UiObject for a child view this is under the PR Esent uiobject.//Get child elements int Getchildcount ()//Counts The Children views immediately under the present uiobject.//get child elements Number of String GetClassName ()//retrieves the ClassName property of the UI element.//gets the current element of class namestring Getcontentde Scription ()//Reads The Content_desc property of the UI elementuiobject getfromparent (uiselector selector)//Creates a New UiObject for a sibling view or a child of the sibling view, relative to the present uiobject.string Getpackagename ( //Reads The View ' s package propertyfinal uiselector getselector ()//Debugging helper. String GetText ()//Reads The Text property of the UIElementrect getvisiblebounds ()//Returns The visible bounds of the view.//gets the visible boundary of the Boolean ischeckable ()//Checks if T He UI element ' s Checkable property is currently true.//can be clicked Boolean isChecked ()//Check if the UI element ' s checked p Roperty is currently true//has been checked for Boolean isclickable ()//Checks if the UI element ' s clickable property is currently TR  Ue.boolean isenabled ()//Checks if the UI element ' s enabled property is currently True.boolean isfocusable ()//Check If the UI element ' s Focusable property is currently True.boolean isFocused ()//Check if the UI element ' s focused prope    Rty is currently Trueboolean islongclickable ()//Check If the view ' s Long-clickable property is currently Trueboolean Isscrollable ()//Check If the view ' s scrollable property is currently Trueboolean isSelected ()//Checks if the UI ele  ment ' s selected property is currently True.boolean Longclick ()//Long clicks the center of the visible bounds of the UI    element//Long Press BooleanLongclickbottomright ()//long clicks Bottom and right corner of the UI Elementboolean longclicktopleft ()//long clicks On the top and left corner of the UI elementboolean performmultipointergesture (pointercoords ... touches)//performs a M Ulti-touch Gesture.boolean performtwopointergesture (Point-StartPoint1, point-StartPoint2, point-EndPoint1, point-Endpoi Nt2, int steps)//generates a two-pointer gesture with arbitrary starting and ending Points.boolean Pinchin (int percent  , int steps)//performs a two-pointer gesture, where each pointer moves diagonally toward the other, from the edges to the  Center of this UiObject. Boolean pinchout (int percent, int steps)//performs a two-pointer gesture, where each pointer Moves diagonally opposite across the other, from the center out towards the edges of the This Uiobject.boolean SetText (String text)//sets the text in a editable field, after clearing the field ' s content.//set the input boolean swipedown (int s TEPS)//performs the SWIPE down action on the Uiobject.boolean swipeleft (int steps)//performs the swipe left action on the Uiobject.boolean swiperight (int steps)//performs the swipe right action on the Uiobject.boolean swipeup (int steps)//performs the SWIP  E up action on the Uiobject.boolean waitforexists (long Timeout)//Waits a specified length of time for a view to become Visible.boolean Waituntilgone (long Timeout)//Waits a specified length of time for a view to become undetectable. Summarize the advantages: All operations can be automated, simple operation does not need to re-sign the test program, and, can test all the programs on the device, such as ~ an app, such as ~ dialing, such as ~ send information and so on for the control positioning, a little bit more than robotium simple disadvantage: Ui Automator requires Android level 16 or more to use, because there are uiautomator tools in level 16 and above if you want to use the Resource-id positioning control, you need the level   18 and above can not be good for Chinese support (does not mean unsupported, third-party jar can be implemented)

Uiautomator Android website translation

Related Article

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.