Words don't say much, the code is affixed first. Anyway, my notes are very detailed ... About the first piece of code in life. (Basetest is written by Android developer)
PackageCom.example.xiaofeng.uiautotest;ImportAndroid.content.Context;ImportAndroid.content.Intent;ImportAndroid.os.RemoteException;ImportAndroid.support.test.InstrumentationRegistry;ImportAndroid.support.test.uiautomator.By;ImportAndroid.support.test.uiautomator.BySelector;ImportAndroid.support.test.uiautomator.UiDevice;ImportAndroid.support.test.uiautomator.UiObject2;ImportAndroid.support.test.uiautomator.Until;ImportAndroid.widget.Button;ImportOrg.junit.Assert;ImportOrg.junit.Before;Import StaticAndroid.support.test.InstrumentationRegistry.getContext;
/** * Created by Nanfeng on 2017/4/24. */Public classbasetest {protectedUideviceMuidevice=NULL;protectedContextMcontext=NULL;//context is the context String in AndroidAPP="Com.maihaoche.bentley.debug";
String base_id = "Com.maihaoche.bentley.debug:id/"; StringBase_id2="Com.maihaoche.bentley.debug";intDisplaytimeout= 5 * 2000; Default interface Refresh Time-out StringUserphone="18868816760"; StringPassword="111111"; @BeforePublic voidSetUp ()throwsremoteexception {Muidevice= Uidevice.getinstance (Instrumentationregistry.getinstrumentation ()); Get Device ObjectMcontext= GetContext (); APP = Getlauncherpackagename ();if(!Muidevice. Isscreenon ()) {//Determine if the screen is awake, if not, wake the screenMuidevice. WakeUp (); }Muidevice. Presshome (); Because it may be in other applications, all press the home key first}protected voidWaitupdate () {//Wait for interface renderingMuidevice. Waitforwindowupdate (APP,Displaytimeout) ; }Public voidOpenapp (String packagename) {//Open app Context context = Instrumentationregistry.getinstrumentation (). GetContext ()
;
Intent Intent = Context.getpackagemanager (). Getlaunchintentforpackage (PackageName); Intent.addflags (Intent.Flag_activity_clear_task);
Context.startactivity (Intent); }/** * The first time to enter the app, walk the Guide page when the logic */protected voidFirstentrance () {NewThread () {@OverridePublic voidRun () {Super. Run (); UiObject2 PowerView =Muidevice. Wait (Until.findobject (By.clazz) (Button.class). Text ("Allow")), 20000);if(PowerView! =NULL{Powerview.click ();//Allow call permission}}}.start (); UiObject2 Skipbutton = Getuibytext ("Skip", 5 * 1000); Get the Skip button from the pageif(Skipbutton! =NULL{//If the page has a "skip" button, you need to skip the boot page and then log in to Skipbutton.click (); Click the Skip button Getuibytext ("Login"). Click (); Click the login button Getuibyid ("Login_phone_txt"). SetText (Userphone); Getuibyid ("Login_password"). SetText (Password);
Enter login name and password//UiObject2 Loginbutton = Getuibyclass (Button.class); UiObject2 Loginbutton = Getuibyid ("Login_login", 3000); Get the login button and wait for 3s assert.assertnotnull ("Didn't get Login button", Loginbutton);
Did not get Login button, throw assertion and Exception loginbutton.click (); Getuibyid ("Login_login"). Click (); Login}}intDelaytime= 10 * 1000; Default wait time to get view PublicUiObject2 Getuibyid (String ID) {returnMuidevice. Wait (Until.findobject (By.res (Base_id2, id)),Delaytime); } PublicUiObject2 Getuibyid (String ID,intWaitTime) {returnMuidevice. Wait (Until.findobject (By.res (Base_id2, id)), waitTime); } PublicUiObject2 Getuibytext (String text) {returnMuidevice. Wait (Until.findobject (by.text (text)),Delaytime); } PublicUiObject2 Getuibytext (String text,intWaitime) {returnMuidevice. Wait (Until.findobject (by.text (text)), waitime); } PublicUiObject2 Getuibyclass (Class uiclass) {returnMuidevice. Wait (Until.findobject (By.clazz (Uiclass)),Delaytime); }/*---------------------------The method you want to consider--------------------------*/ PublicUiObject2 findobject (byselector selector)throwsinterruptedexception {UiObject2 Object =NULL;intTimeout = 30000;intDelay = 1000;LongTime = System.currenttimemillis (); while(Object = =NULL) {object =Muidevice. Findobject (selector); Thread.Sleep (delay);if(System.currenttimemillis ()-Timeout > Time) { Break; }
}returnObject }//Private UiObject Getuibyid (String ID) {//Return Muidevice.findobject (New Uiselector (). ResourceId (base_id
+ ID)); }////Private UiObject Getuibytext (String text) {//Return Muidevice.findobject (New Uiselector (). Text (Te
XT)); }////Private String Getlauncherpackagename () {////Create launcher Intent//FINAL Intent inte
NT = new Intent (intent.action_main);
Intent.addcategory (Intent.category_home); //Use Packagemanager to get the Launcher package name//Packagemanager PM = instrumentationregistry.
GetContext (). Getpackagemanager ();
ResolveInfo ResolveInfo = pm.resolveactivity (Intent, packagemanager.match_default_only);
return resolveInfo.activityInfo.packageName; // }
}
PackageCom.example.xiaofeng.uiautotest;ImportAndroid.content.Context;ImportAndroid.support.test.espresso.InjectEventSecurityException;ImportANDROID.SUPPORT.TEST.RUNNER.ANDROIDJUNIT4;ImportAndroid.support.test.uiautomator.By;ImportAndroid.support.test.uiautomator.Configurator;ImportAndroid.support.test.uiautomator.SearchCondition;ImportAndroid.support.test.uiautomator.StaleObjectException;ImportAndroid.support.test.uiautomator.UiObject2;ImportAndroid.support.test.uiautomator.UiObjectNotFoundException;ImportAndroid.support.test.uiautomator.Until;ImportAndroid.util.Log;ImportAndroid.view.WindowManager;ImportAndroid.widget.Button;ImportAndroid.widget.TextView;ImportOrg.junit.Assert;ImportOrg.junit.Test;ImportOrg.junit.runner.RunWith;ImportJava.util.List;ImportJava.util.Random; /** * Created by Datou on 17/4/26. Used to create a pure logistics Waybill */@RunWith (ANDROIDJUNIT4.class)Public classWuliucaseextendsBasetest {//base is a piece of code that encapsulates a subset of the functionality, and can be referenced directly after inheritance @TestPublic voidTest1 ()throwsuiobjectnotfoundexception,injecteventsecurityexception{Openapp (APP); Open app Waitupdate ();
Wait for the page to render Configurator.getinstance (). Setactionacknowledgmenttimeout (200).
/*--------------to enter the app for the first time via the boot page-----------*/firstentrance (); /*---------------Click Logistics Services-----------------------*/Getuibytext ("Logistics Services", (). click (); /*---------------Get the phone box prompt to get the user's corresponding permissions, have, select Allow--------------*/UiObject2 OK =Muidevice. Findobject (By.clazz (Button.class). Textcontains ("Allow"));if(OK! =NULL){Muidevice. Wait (Until.findobject (By.clazz) (Button.class). Textcontains ("Allow"). Click (); } getuibytext ("Originating City"). Click ();
Getuibytext ("Zhejiang province", "."). Click (); Getuibytext ("Hangzhou City", +). Click (); Getuibytext ("Destination City"). Click ();
Getuibytext ("Anhui province", "."). Click (); Getuibytext ("Hefei", +). Click (); Addcarinfo (); Call to add vehicle information getuibytext ("Inquiry Tariff"). Click (); Click to inquire Tariff/*------------into the Inquiry results page----------------*/Downorder (); Call the Order Getuibytext ("Shipping Time"). Click ();//select Shipping Time Getuibytext ("Done"). Click (); In the pop-up Time selection box Click the Finish button, because the others are more difficult, haha Getuibyid ("Ed_name"). SetText ("Big Head")//Enter the name of the person Getuibyid ("Ed_tel"). SetText ("15212099082")///Enter the departure mobile number//------------need to swipe the screen---------*/intHeight = ((windowmanager)Mcontext. Getsystemservice (Context.Window_service). Getdefaultdisplay (). GetHeight ();Muidevice. Swipe (0,height-100,0,0,100); The Swip method is the whole screen slide method, the five parameters are the coordinates of the starting point and the coordinates of the destination, and the speed of the slide. Because the x-coordinate is relatively motionless, the relative coordinates are selected as the y-coordinate of the 0//start point because the y-axis may cause the screen to slide out of the process of many phones if it starts sliding from the bottom "height" of the screen, so writing "height-100" means that the bottom of the screen starts to slide at one o'clock. Swipe to the top of the screen Getuibyid ("Ed_detail"). SetText ("I am the detailed vehicle inspection address"); Enter the detailed address information of the waybill, but in order to prevent consistent every time, you can add a random number after the fixed textintindex =NewRandom (). Nextint (10000);//random is a method of obtaining a random number in Java, and Nextint is a number in a random number of 0-10000, String flagstr ="I am an Android automated test run out of pure logistics list"+ index; Pin the note to a template, then define/Declare an object FLAGSTR to reference it Getuibyid ("Ed_notice"). SetText (FLAGSTR); The first few lines of this pick-up address and random number of text all crammed into the detailed address of this field getuibytext ("Submit Waybill"). Click ();//Click submit Waybill button//muidevice.wait (Until.findobject (By.clazz (Button.class). Textcontains ("confirm")). Click () ; Confirm to submit Waybill Getuibytext ("Confirm"). Click ();//In the dialog box to confirm the submission of the waybill, enter the waybill to be paid page String orderId = Getuibyid ("Tv_orderid"). GetText ();//Obtain the Waybill ID of the pending Payment page after the submission of the label (equal to the position of the Waybill ID, to get the value of this ID; the equals sign is declared as a new object for the acquired order ID, which makes it easy to call later)/*-------- Below is the entry to my shipping list----------*/Getuibyid ("LEFT_BTN"). Click (); Click the top left corner of the page to return to the button Getuibytext ("My Waybill"). Click ();
Click on the "My Waybill" button in the top right corner to enter my shipping list page//Muidevice.swipe (0,100,0,400,50); Below is the invoice ID of the pending Payment page obtained in the previous search on my list page and there is no consistent waybill, if any, that is, this bytext value is not empty, representing the previous Waybill creation success//UiObject2 Bytext = Getuibytext (Order
id,5 * 1000); Assert.assertnull ("No Matching orders found", bytext);//assert that the waybill is not located, print this message//UiObject2 order = Getuibyid ("list"). Find
Object (By.desc ("waybill number"));
Assert.assertnull ("No object Received", order);
UiObject2 order = Getuibyid ("tv_id");
Assert.assertfalse ("No Matching orders found", order! = null && order.gettext (). Equals (OrderId)); /*----------in order to see the last run to that page, so set on this page to stay in 10s--------------*/Try{Thread.Sleep (10 * 1000);//thread Sleep 10s}Catch(Interruptedexception e) {E.printstacktrace (); If you do not stay in the 10s to print the exception thrown}}/** * The next order method recursion (because this method in the loop is also reused, so the encapsulation process is: Select the code snippet to be encapsulated, right-click-refactor-extract -method-Input Method Name (first letter lowercase)-click OK. Package success) */private voidDownorder () {UiObject2 Xiadan = Getuibytext ("Order");//Get the object (because you want to do something else with this object, so you can get it: Select the object you want to get--click "Alt+return"-introduce...-enter-to rename the object-enter, the object gets successful. )if(Xiadan! =NULL) {Xiadan.click (); }Else{Getuibyid ("LEFT_BTN"). Click (); Return to Parent page Getuibyid ("Btn_delete"). Click (); Remove the added vehicle Getuibyid ("BTN_OK"). Click (); Confirm deletion of Addcarinfo (); Continue adding vehicle getuibytext ("Inquiry Tariff"). Click ();
Click to inquire Tariff downorder (); }}//Add vehicle information and other methodsprivate voidAddcarinfo () {Getuibytext ("Add vehicle information"). Click (); Getuibyid ("Item_type"). Click (); Getuibytext ("Medium/domestic", +). Click (); Getuibytext ("Audi", +). Click (); Getrandomuifromlist ("Recycler_choose", TextView.class). Click ();
Randomly selected car system Getcartypeclick (); Getuibyid ("Ed_car_num"). SetText ("1"); The number of vehicles entered is 1 units getuibytext ("Confirm Add", +). Click (); Confirm Add}private voidGetcartypeclick () {UiObject2 Cartype = getrandomuifromlist ("Recycler_choose", TextView.class);//random selection of modelsif(Cartype.gettext (). EndsWith ("Custom")) {Getcartypeclick ();