標籤:port idt 9.png display rup 視圖 and key baidu
Android自動化測試-UiAutomator環境搭建
一、環境準備
1. 安裝android sdk,並配置環境變數
2. 安裝android studio,國內訪問官網受限,如果下載不到,可以到我的百度雲端硬碟下載:
https://pan.baidu.com/s/1bpq5wK3
此雲端硬碟中有uiautomator2所依賴的jar包,可以同時下載
二、建立Android Studio工程
建立一個project,輸入application name,下一步,
預設選擇,下一步,
選擇 empty activity:
最後finish之後,切換到project視圖;
右擊工程,建立一個libs,並把網盤中下載的uiautomator依賴的jar包,copy進來,並添加依賴,
Add As Library之後,會彈出一個小框,選擇app,點擊OK
這樣我們的工程就建好了,左上方,把我們的project模式切換成android模式,
現在android視圖模式下,介面就比較簡潔直觀了,如所示:標註android test的地方,就是我們要寫測試案例的包,
新家一個java class,輸入class name,現在我們就可以開開心心的寫測試代碼了
三、測試執行個體
下面我們寫一個例子,啟動模擬器,模擬器home上有個chrome瀏覽器,操作步驟:點擊chrome-輸入www.baidu.com-enter;
點擊android studio上的 AVD manager,就可以啟動模擬器,模擬器介面如下:
測試案例:
1. 點擊chrome
2. 輸入www.baidu.com
3. Enter
代碼如下:
寫好測試案例之後,我們就可以運行了,在運行之前,我們先看下回合組態:
在設定檔中,一定要有如下一行代碼,如果沒有,可以自己加上:
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
現在就可以運行了,開啟你的模擬器,看下介面有什麼效果:
完整代碼如下:
1 import android.app.Instrumentation; 2 import android.support.test.InstrumentationRegistry; 3 import android.support.test.runner.AndroidJUnit4; 4 import android.support.test.uiautomator.UiDevice; 5 import android.support.test.uiautomator.UiObject; 6 import android.support.test.uiautomator.UiObjectNotFoundException; 7 import android.support.test.uiautomator.UiSelector; 8 import android.view.KeyEvent; 9 10 import org.junit.Before;11 import org.junit.Test;12 import org.junit.runner.RunWith;13 14 /**15 * Created by tianxing on 2017/8/15.16 */17 18 @RunWith(AndroidJUnit4.class)19 public class helloworld {20 21 UiDevice uiDevice;22 Instrumentation instrumentation;23 24 @Before25 public void setUp(){26 instrumentation = InstrumentationRegistry.getInstrumentation();27 uiDevice = UiDevice.getInstance(instrumentation);28 }29 30 @Test31 public void launchChrome(){32 UiObject chrome = uiDevice.findObject(new UiSelector().text("Chrome"));33 UiObject searchContent = uiDevice.findObject(new UiSelector().text("Search or type URL"));34 35 try {36 chrome.click();37 sleep(2000);38 searchContent.setText("www.baidu.com");39 uiDevice.pressKeyCode(KeyEvent.KEYCODE_ENTER);40 } catch (UiObjectNotFoundException e) {41 e.printStackTrace();42 }43 44 }45 46 public void sleep(int mint){47 try{48 Thread.sleep(mint);49 }catch (InterruptedException e){50 e.printStackTrace();51 }52 }53 54 }
View Code
Android自動化測試-UiAutomator環境搭建