作爲所有測試用例的超類,UiAutomatorTestCase繼承於junit.framework.TestCase,遵循setUp,test,tearDown的測試流程,支持斷言使用,負責基礎的框架支持,包含執行過程的參數獲取,實例獲取及斷言使用。對應api解析如下:
1、參數獲取:
返回值
方法及說明
Bundle
getParams()
在執行UIAutomator時,可以使用-e 給執行過程指定參數,所有鍵值對存儲於參數Bundle中,在測試過程中通過getParams()得到該Bundle
用法:
假設我需要想jar包傳三個參數,String uiserName,String password,long runTime,則對應的命令應該如下:
public void test1() throws Exception {
Bundle bundle=getParams();//獲取鍵值對
String userName=bundle.getString("userName");
String password=bundle.getString("password");
long runTime=Long.parseLong(bundle.getString("runTime"));
System.out.println(runTime+"======="+password+"========"+userName);
}
2、實例獲取:
返回值
方法及說明
UiDevice
getUiDevice()
取得當前設備實例,等效於使用Uidevice.getInstance()
IAutomationSupport
getAutomationSupport()
取得uiautomator實現的IAutomationSupport實例,用以向結果添加INSTRUMENTATION_STATUS標誌的日誌信息
用法:
public void testDevice() {
//獲取手機設備的實例
UiDevice device1 = UiDevice.getInstance();
device1.pressBack();
//獲取手機設備的實例另一種方法
UiDevice device2 = getUiDevice();
device2.pressBack();
}
3、流程執行:
返回值
方法及說明
void
setup()
測試前環境準備,在同一個類中與每個testCase前執行,一般被用戶覆寫,用以測試時的初始化準備放置於該方法內進行
void
sleep(long ms)
休眠指定時間,等效與使用SystemClock.sleep(long ms)
void
tearDown()
測試後收尾工作,在同一個類中與每個testCase後執行,一般被用戶覆寫,用以處理執行結果,保存數據,還原測試前環境
用法:
public void setup() {
System.out.println("開始測試");
}
public void tearDown() {
System.out.println("結束測試");
}
public void testSleep() {
//休眠1s
sleep(1000);
}
4、斷言支持:
返回值
方法及說明
void
assertXXX()系列
繼承於junit.framework.Assert,常用斷言來檢查當前的測試環境狀態,如斷言失敗,則認爲case執行失敗,case執行終端,進入tearDown()
測試腳本:
package com.uiautomator.demo;
import android.os.Bundle;
import com.android.uiautomator.core.UiDevice;
import com.android.uiautomator.testrunner.UiAutomatorTestCase;
public class Home extends UiAutomatorTestCase {
public static void main(String[] args) {
String testClass, testName;
testClass = "com.uiautomator.demo.Home";
testName = "";
new UiAutomatorHelper(testClass, testName);
}
public void setup() {
System.out.println("開始測試");
}
public void tearDown() {
System.out.println("結束測試");
}
public void testSleep() {
//休眠1s
sleep(1000);
assertEquals("預期的", "真實的");
}
public void testDevice() {
// 獲取手機設備的實例
UiDevice device1 = UiDevice.getInstance();
device1.pressBack();
// 獲取手機設備的實例另一種方法
UiDevice device2 = getUiDevice();
device2.pressBack();
}
public void test1() throws Exception {
Bundle bundle = getParams();// 獲取鍵值對
String userName = bundle.getString("userName");
String password = bundle.getString("password");
long runTime = Long.parseLong(bundle.getString("runTime"));
System.out.println(runTime + "=======" + password + "========"
+ userName);
}
}