關於Uiautomator的學習曆程(1)

來源:互聯網
上載者:User

話不多說,代碼先貼上。反正我備忘的都很詳細啦。。。關於人生中的第一段代碼。(BaseTest是android開發寫的)

package com.example.xiaofeng.uiautotest;import android.content.Context;import android.content.Intent;import android.os.RemoteException;import android.support.test.InstrumentationRegistry;import android.support.test.uiautomator.By;import android.support.test.uiautomator.BySelector;import android.support.test.uiautomator.UiDevice;import android.support.test.uiautomator.UiObject2;import android.support.test.uiautomator.Until;import android.widget.Button;import org.junit.Assert;import org.junit.Before;import static android.support.test.InstrumentationRegistry.getContext;/** * Created by nanfeng on 2017/4/24. */public class BaseTest {    protected UiDevice mUIDevice = null;    protected Context mContext = null;//Context是android中上下文    String APP = "com.maihaoche.bentley.debug";    //    String BASE_ID = "com.maihaoche.bentley.debug:id/" ;    String BASE_ID2 = "com.maihaoche.bentley.debug" ;    int displayTimeOut = 5 * 2000 ;  //預設的介面重新整理逾時時間    String userPhone = "18868816760" ;    String password = "111111" ;    @Before    public void setUp() throws RemoteException {        mUIDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());  //獲得device對象        mContext = getContext();//        APP = getLauncherPackageName() ;        if(!mUIDevice.isScreenOn()){  //判斷螢幕是否喚醒狀態,如果非,喚醒螢幕            mUIDevice.wakeUp();        }        mUIDevice.pressHome();  //因為可能會處於其他的應用中,所有先按home鍵    }    protected void waitUpdate(){   //等待介面渲染        mUIDevice.waitForWindowUpdate(APP,displayTimeOut) ;    }    public void openApp(String packageName) {  //開啟APP        Context context = InstrumentationRegistry.getInstrumentation().getContext();        Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);        context.startActivity(intent);    }    /**     * 第一次進APP,走引導頁時的邏輯     */    protected void firstEntrance() {        new Thread(){            @Override            public void run() {                super.run();                UiObject2 powerView = mUIDevice.wait(Until.findObject(By.clazz(Button.class).text("允許")), 20000);                if (powerView != null) {                    powerView.click(); //允許打電話許可權                }            }        }.start();        UiObject2 skipButton = getUiByText("跳過",5 * 1000);  //從頁面擷取"跳過"按鈕        if (skipButton != null){   //如果頁面存在"跳過"按鈕,則需要跳過引導頁,然後登陸            skipButton.click();  //點擊跳過按鈕            getUiByText("登入").click();   //點擊登陸按鈕            getUiById("login_phone_txt").setText(userPhone);            getUiById("login_password").setText(password);   //錄入登入名稱和密碼//            UiObject2 loginButton = getUiByClass(Button.class);            UiObject2 loginButton = getUiById("login_login",3000) ;   //擷取登陸按鈕,等待3s            Assert.assertNotNull("沒有拿到登入按鈕",loginButton);  //沒有拿到登陸按鈕,拋出斷言和異常            loginButton.click();//            getUiById("login_login").click(); //登入        }    }    int delayTime = 10 * 1000 ;  //預設等待擷取View的時間    public UiObject2 getUiById(String id){        return mUIDevice.wait(Until.findObject(By.res(BASE_ID2, id)), delayTime);    }    public UiObject2 getUiById(String id, int waitTime){        return mUIDevice.wait(Until.findObject(By.res(BASE_ID2, id)), waitTime);    }    public UiObject2 getUiByText(String text){        return mUIDevice.wait(Until.findObject(By.text(text)), delayTime);    }    public UiObject2 getUiByText(String text, int waiTime){        return mUIDevice.wait(Until.findObject(By.text(text)), waiTime);    }    public UiObject2 getUiByClass(Class uiClass){        return mUIDevice.wait(Until.findObject(By.clazz(uiClass)),delayTime);    }    /*---------------------------待斟酌的方法--------------------------*/    public UiObject2 findObject(BySelector selector) throws InterruptedException {        UiObject2 object = null;        int timeout = 30000;        int delay = 1000;        long time = System.currentTimeMillis();        while (object == null) {            object = mUIDevice.findObject(selector);//            Thread.sleep(delay);            if (System.currentTimeMillis() - timeout > time) {                break;            }        }        return object;    }//    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(text));//    }////    private String getLauncherPackageName() {//        // Create launcher Intent//        final Intent intent = 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;//    }}






package com.example.xiaofeng.uiautotest;import android.content.Context;import android.support.test.espresso.InjectEventSecurityException;import android.support.test.runner.AndroidJUnit4;import android.support.test.uiautomator.By;import android.support.test.uiautomator.Configurator;import android.support.test.uiautomator.SearchCondition;import android.support.test.uiautomator.StaleObjectException;import android.support.test.uiautomator.UiObject2;import android.support.test.uiautomator.UiObjectNotFoundException;import android.support.test.uiautomator.Until;import android.util.Log;import android.view.WindowManager;import android.widget.Button;import android.widget.TextView;import org.junit.Assert;import org.junit.Test;import org.junit.runner.RunWith;import java.util.List;import java.util.Random;/** * Created by datou on 17/4/26.用於建立純物流運單 */@RunWith(AndroidJUnit4.class)public class WuLiuCase extends BaseTest {  //Base是一個封裝了一部分功能的代碼,繼承後就可以直接引用其中的方法啦    @Test    public void test1() throws UiObjectNotFoundException,InjectEventSecurityException{        openApp(APP);  //開啟app        waitUpdate();   //等待頁面渲染        Configurator.getInstance().setActionAcknowledgmentTimeout(2000).setKeyInjectionDelay(200);        /*--------------第一次進入APP需要通過引導頁-----------*/        firstEntrance();        /*---------------點擊物流服務-----------------------*/        getUiByText("物流服務",5000).click();        /*---------------擷取是否有手機彈框提示擷取使用者對應許可權,有,選擇允許--------------*/        UiObject2 ok = mUIDevice.findObject(By.clazz(Button.class).textContains("允許"));        if (ok != null){            mUIDevice.wait(Until.findObject(By.clazz(Button.class).textContains("允許")),2000).click();        }        getUiByText("始發城市").click();       // getUiByText("浙江省",2000).click();        getUiByText("杭州市",2000).click();        getUiByText("目的城市").click();        // getUiByText("安徽省",2000).click();        getUiByText("合肥市",2000).click();        addCarInfo(); //調用添加車輛資訊        getUiByText("查詢運價").click(); //點擊查詢運價        /*------------進入詢價結果頁面啦----------------*/        downOrder(); //調用下單        getUiByText("發運時間").click();//選擇發運時間        getUiByText("完成").click(); //在彈出的時間選擇框中點擊完成按鈕,因為其他的都比較難,哈哈        getUiById("ed_name").setText("大頭");//錄入發車人姓名        getUiById("ed_tel").setText("15212099082");//錄入發車人手機號碼        /*------------此時需要滑動螢幕---------*/        int height = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getHeight() ;        mUIDevice.swipe(0,height - 100,0,0,100) ;        //swip方法是整個螢幕滑動的方法,裡面的五個參數分別是起始點的座標和終點的座標以及滑動的速度。因為x座標是相對不動的,所以相對座標都選為0        //起始點的y軸座標是因為y軸如果從螢幕的底端"height"開始滑動可能會導致螢幕滑動出很多手機的進程等內容,所以寫成"height-100"表示螢幕底端向上一點開始滑動,滑動至螢幕頂端        getUiById("ed_detail").setText("我是提車驗車詳細地址");  //錄入運單詳細地址資訊,但是為了防止每次都一致,可以在固定的文本後添加隨機數        int index = new Random().nextInt(10000) ;//Random是java中擷取隨機數的方法,nextInt中表示的是隨機數為0-10000中的某個數        String flagStr = "我是android自動化測試跑出來的純物流單子" + index ; //把備忘固定為一個模版,然後定義/聲明一個對象flagStr去引用它        getUiById("ed_notice").setText(flagStr); //把前幾行的這個提車詳細地址和隨機數的文本全部塞進詳細地址這個欄位        getUiByText("提交運單").click();//點擊提交運單按鈕//        mUIDevice.wait(Until.findObject(By.clazz(Button.class).textContains("確認")),2000).click(); //確認提交運單        getUiByText("確認").click();//在彈出的對話方塊中確定提交運單,進入運單待付款頁面        String orderId = getUiById("tv_orderid").getText();//擷取提交運單後的待付款頁面的本運單id,(等號後面的意思是定位運單id的位置,擷取這個id的值;等號前面是把這個擷取的訂單id聲明為一個新的對象,方便後面調用)        /*--------下面是進入我的運單列表頁面----------*/        getUiById("left_btn").click();   //點擊頁面左上方返回按鈕        getUiByText("我的運單").click();   //點擊右上方"我的運單"按鈕,進入我的運單列表頁面//        mUIDevice.swipe(0,100,0,400,50) ;        //下面是通過前面擷取的待付款頁面的運單id在我的運單列表頁面進行尋找又沒有對應一致的運單,如果有,即這個bytext值不為空白,代表前面的運單建立成功//        UiObject2 byText = getUiByText(orderId,5 * 1000);//        Assert.assertNull("沒有找到匹配的訂單",byText);//斷言這個運單沒有尋找到,則列印此提示資訊//        UiObject2 order = getUiById("list").findObject(By.desc("運單編號"));//        Assert.assertNull("沒有拿到對象",order);////        UiObject2 order = getUiById("tv_id");//        Assert.assertFalse("沒有找到匹配的訂單",order != null && order.getText().equals(orderId));        /*----------為了查看最後運轉到那個頁面,所以設定在這個頁面停留10s中--------------*/        try {            Thread.sleep(10 * 1000); //線程睡眠10s        } catch (InterruptedException e) {            e.printStackTrace();    //如果沒有停留10s中就列印拋出的異常        }    }    /**     * 下單方法 遞迴(因為這個方法在迴圈裡還要被重複用到,所以封裝一下,封裝的過程是:選中要封裝的程式碼片段,右鍵-refactor-extract-method-錄入方法名(首字母小寫)-點擊OK。封裝成功)     */    private void downOrder() {        UiObject2 xiadan = getUiByText("下單");//擷取對象(因為後面要對這個對象進行其他動作,所以可以進行擷取,擷取的步驟是:選中要擷取的對象-點擊"alt+return"-Introduce...-enter-給對象重新命名-enter,對象擷取成功。)        if (xiadan != null) {            xiadan.click();        }else {            getUiById("left_btn").click(); //返回上級頁面            getUiById("btn_delete").click(); //刪除添加的車輛            getUiById("btn_ok").click(); // 確認刪除            addCarInfo(); //繼續添加車輛            getUiByText("查詢運價").click(); //點擊查詢運價            downOrder();        }    }    //添加車輛資訊等方法    private void addCarInfo() {            getUiByText("添加車輛資訊").click();            getUiById("item_type").click();            getUiByText("中規/國產",3000).click();            getUiByText("奧迪",2000).click();            getRandomUiFromList("recycler_choose",TextView.class).click(); //隨機播放車系            getCarTypeClick();            getUiById("ed_car_num").setText("1"); //輸入車輛數量為1輛            getUiByText("確認添加",3000).click(); //確認添加    }    private void getCarTypeClick(){        UiObject2 carType = getRandomUiFromList("recycler_choose", TextView.class);//隨機播放車型        if (carType.getText().endsWith("自訂")){            getCarTypeClick();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.