背景:在Eclipse中不能直接運行Uiautomator工程,所以每次編寫一份用例都要進行手動輸入命令,很煩。調試起來不僅繁瑣還浪費時間。網上找到一份快速調試的代碼UiAutomatorHelper,可將這幾步進行簡化很方便(當然也可以使用bat文件,相比之下還是這個方便)。
create buildxml file:android create uitest-project -n <jar_name> -t <androidId> -p <path>
ant build xmlfile:ant build
push jarFile:adb push <jar_path> data/local/tmp
Run Test:adb shell uiautomator runtest <jar_name> --nohup -c <testClass.testName>
步驟:將UiAutomatorHelper.java放到工程目錄下(與測試腳本同目錄),在測試腳本中寫個main方法。然后Run as ->java application即可
Display.java
package com.change.display; import java.io.File; import java.io.IOException; import android.os.RemoteException; import com.android.uiautomator.core.UiDevice; import com.android.uiautomator.core.UiObject; import com.android.uiautomator.core.UiObjectNotFoundException; import com.android.uiautomator.core.UiSelector; import com.android.uiautomator.testrunner.UiAutomatorTestCase; public class Display extends UiAutomatorTestCase{ public static void main(String [] args ){ String jarName="ChangeFont"; String testClass="com.change.display.Display"; String testName="test1"; String androidId="1"; new UiAutomatorHelper(jarName, testClass, testName, androidId); } public void test1 () throws UiObjectNotFoundException, RemoteException, IOException{ //Device wake up UiDevice.getInstance().wakeUp(); //sleep 3s sleep(3000); //Open the settings Runtime.getRuntime().exec("am start -n com.android.settings/.Settings"); //Click on display try{ UiObject display = new UiObject(new UiSelector().text("顯示")); display.click(); sleep(3000); }catch(Exception e){ e.printStackTrace(); } //Select font UiObject fs = new UiObject(new UiSelector().text("字體大小")); fs.clickAndWaitForNewWindow(); //Change font UiObject size = new UiObject(new UiSelector().text("超大")); size.click(); //Screen shot sleep(3000); Runtime.getRuntime().exec("screencap -p /sdcard/test.png"); //Enter Home interface sleep(3000); getUiDevice().pressHome(); getUiDevice().takeScreenshot(new File("/sdcard/test1.png")); sleep(2000); } }
UiAutomatorHelper.java (正常流情況,未考慮異常及其他情況)
package com.change.display; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class UiAutomatorHelper { private static String android_id="1"; private static String jar_name=""; private static String test_class=""; private static String test_name=""; private static String workspace_path;
public UiAutomatorHelper(String jarName,String testClass,String testName,String androidId) { System.out.println("---------start--uiautomator--debug"); workspace_path = getWorkSpace(); System.out.println("WorkSpace : \n" + getWorkSpace()); jar_name = jarName; test_class = testClass; test_name = testName; android_id = androidId; crateBuildXML(); System.out.println("----------create build.xml successful"); antBuildXML(); System.out.println("----------ant build.xml successful"); pushJarFile(); System.out.println("----------push jarFile successful");
runTestCase(); System.out.println("**************************"); System.out.println("--------FINISH DEBUG------"); System.out.println("**************************"); } // Create build.xml file private void crateBuildXML() { execCmd(" cmd /c android create uitest-project -n "+jar_name+" -t "+android_id+" -p "+workspace_path); } //Ant build.xml file private void antBuildXML() { execCmd("cmd /c ant build"); } //Push jarFile to device private void pushJarFile() { String localPath = workspace_path +"\\bin\\"+ jar_name +".jar"; System.out.println("------jar包路徑:"+localPath); execCmd("adb push "+ localPath + " /data/local/tmp/"); } //Run test case private void runTestCase() { String runString="adb shell uiautomator runtest "; execCmd(runString+jar_name+".jar "+"--nohup -c "+test_class+"#"+test_name); } public void execCmd(String cmd){ System.out.println("------execCmd: " + cmd); try { Process p = Runtime.getRuntime().exec(cmd); //normal InputStream input = p.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); String line = ""; while ((line=reader.readLine()) != null) { System.out.println(line); } //error InputStream errorInput =p.getErrorStream(); BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorInput)); String eline = ""; while ((eline=errorReader.readLine())!= null) { System.out.println(eline); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String getWorkSpace(){ //getCanonicalPath() and getAbsolutePath() String pathFile = new File("").getAbsolutePath(); return pathFile; } }
注:若編譯過程中出現:android不是內部命令,build.xml is a directory !請注意環境變量(SDK,ANT)是否配置正確
順帶附上原始UiAutomatorHelper.java代碼

package com.change.display; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class UiAutomatorHelper { // 以下參數需要配置,用例集id,用例id,安卓id private static String android_id = "3"; private static String jar_name = ""; private static String test_class = ""; private static String test_name = ""; // 工作空間不需要配置,自動獲取工作空間目錄 private static String workspace_path; public UiAutomatorHelper() { workspace_path = getWorkSpase(); System.out.println("---工作空間:\t\n" + getWorkSpase()); } /** * 需求:UI工程調試構造器,輸入jar包名,包名,類名,用例名 * @param jarName * @param testClass * @param testName * @param androidId */ public UiAutomatorHelper(String jarName, String testClass, String testName,String androidId) { System.out.println("-----------start--uiautomator--debug-------------"); workspace_path = getWorkSpase(); System.out.println("----工作空間:\t\n" + getWorkSpase()); jar_name = jarName; test_class = testClass; test_name = testName; android_id = androidId; runUiautomator(); System.out.println("*******************"); System.out.println("---FINISH DEBUG----"); System.out.println("*******************"); } /** * 需求:build 和 復制jar到指定目錄 * @param jarName * @param testClass * @param testName * @param androidId * @param isRun */ public UiAutomatorHelper(String jarName, String testClass, String testName,String androidId,String ctsTestCasePath){ System.out.println("-----------start--uiautomator--debug-------------"); workspace_path = getWorkSpase(); System.out.println("----工作空間:\t\n" + getWorkSpase()); jar_name = jarName; test_class = testClass; test_name = testName; android_id = androidId; buildUiautomator(ctsTestCasePath); System.out.println("*******************"); System.out.println("---FINISH DEBUG----"); System.out.println("*******************"); } // 運行步驟 private void runUiautomator() { creatBuildXml(); modfileBuild(); buildWithAnt(); if (System.getProperty("os.name").equals("Linux")) { pushTestJar(workspace_path + "/bin/" + jar_name + ".jar"); }else{ pushTestJar(workspace_path + "\\bin\\" + jar_name + ".jar"); } if (test_name.equals("")) { runTest(jar_name, test_class); return; } runTest(jar_name, test_class + "#" + test_name); } // 1--判斷是否有build public boolean isBuild() { File buildFile = new File("build.xml"); if (buildFile.exists()) { return true; } // 創建build.xml execCmd("cmd /c android create uitest-project -n " + jar_name + " -t "+ android_id + " -p " + workspace_path); return false; } // 創建build.xml public void creatBuildXml() { execCmd("cmd /c android create uitest-project -n " + jar_name + " -t "+ android_id + " -p " + "\""+workspace_path+ "\""); } // 2---修改build public void modfileBuild() { StringBuffer stringBuffer = new StringBuffer(); try { File file = new File("build.xml"); if (file.isFile() && file.exists()) { // 判斷文件是否存在 InputStreamReader read = new InputStreamReader( new FileInputStream(file)); BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; while ((lineTxt = bufferedReader.readLine()) != null) { if (lineTxt.matches(".*help.*")) { lineTxt = lineTxt.replaceAll("help", "build"); // System.out.println("修改后: " + lineTxt); } stringBuffer = stringBuffer.append(lineTxt + "\t\n"); } read.close(); } else { System.out.println("找不到指定的文件"); } } catch (Exception e) { System.out.println("讀取文件內容出錯"); e.printStackTrace(); } System.out.println("-----------------------"); // 修改后寫回去 writerText("build.xml", new String(stringBuffer)); System.out.println("--------修改build完成---------"); } // 3---ant 執行build public void buildWithAnt() { if (System.getProperty("os.name").equals("Linux")) { execCmd("ant"); return; } execCmd("cmd /c ant"); } // 4---push jar public void pushTestJar(String localPath) { localPath="\""+localPath+"\""; System.out.println("----jar包路徑: "+localPath); String pushCmd = "adb push " + localPath + " /data/local/tmp/"; System.out.println("----" + pushCmd); execCmd(pushCmd); } // 運行測試 public void runTest(String jarName, String testName) { String runCmd = "adb shell uiautomator runtest "; String testCmd = jarName + ".jar " + "--nohup -c " + testName; System.out.println("----runTest: " + runCmd + testCmd); execCmd(runCmd + testCmd); } public String getWorkSpase() { File directory = new File(""); String abPath = directory.getAbsolutePath(); return abPath; } /** * 需求:執行cmd命令,且輸出信息到控制台 * @param cmd */ public void execCmd(String cmd) { System.out.println("----execCmd: " + cmd); try { Process p = Runtime.getRuntime().exec(cmd); //正確輸出流 InputStream input = p.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader( input)); String line = ""; while ((line = reader.readLine()) != null) { System.out.println(line); saveToFile(line, "runlog.log", false); } //錯誤輸出流 InputStream errorInput = p.getErrorStream(); BufferedReader errorReader = new BufferedReader(new InputStreamReader( errorInput)); String eline = ""; while ((eline = errorReader.readLine()) != null) { System.out.println(eline); saveToFile(eline, "runlog.log", false); } } catch (IOException e) { e.printStackTrace(); } } /** * 需求:寫如內容到指定的文件中 * * @param path * 文件的路徑 * @param content * 寫入文件的內容 */ public void writerText(String path, String content) { File dirFile = new File(path); if (!dirFile.exists()) { dirFile.mkdir(); } try { // new FileWriter(path + "t.txt", true) 這里加入true 可以不覆蓋原有TXT文件內容 續寫 BufferedWriter bw1 = new BufferedWriter(new FileWriter(path)); bw1.write(content); bw1.flush(); bw1.close(); } catch (IOException e) { e.printStackTrace(); } } public void saveToFile(String text,String path,boolean isClose) { File file=new File("runlog.log"); BufferedWriter bf=null; try { FileOutputStream outputStream=new FileOutputStream(file,true); OutputStreamWriter outWriter=new OutputStreamWriter(outputStream); bf=new BufferedWriter(outWriter); bf.append(text); bf.newLine(); bf.flush(); if(isClose){ bf.close(); } } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 需求:編譯和復制jar包指定文件 * @param newPath */ private void buildUiautomator(String newPath) { creatBuildXml(); modfileBuild(); buildWithAnt(); //復制文件到指定文件夾 copyFile(workspace_path + "\\bin\\" + jar_name + ".jar", newPath); } /** * 復制單個文件 * @param oldPath String 原文件路徑 如:c:/fqf.txt * @param newPath String 復制后路徑 如:f:/fqf.txt * @return boolean */ public void copyFile(String oldPath, String newPath) { System.out.println("源文件路徑:"+oldPath); System.out.println("目標文件路徑:"+newPath); try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { //文件存在時 InputStream inStream = new FileInputStream(oldPath); //讀入原文件 FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1444]; while ( (byteread = inStream.read(buffer)) != -1) { bytesum += byteread; //字節數 文件大小 System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); fs.close(); } } catch (Exception e) { System.out.println("復制單個文件操作出錯"); e.printStackTrace(); } } }
附批處理實現快速調試:
運行測試暫未加入批處理中,可根據自身需求加入
@echo off
rem 工程目錄,Jar包名字,編譯后的jar包位置,當前路徑 set reso=G:\WorkSpace\DisplayCase
set jar=ChangeFont set jarLoction=%reso%\bin\%jar%.jar set dest=%~dp0 cd /d %reso% rem 一行實現 rem android create uitest-project -n %jar% -t 1 -p %reso% && ant build && adb push %jarLoction% /data/local/tmp/ &© %jarLoction% %dest% &pause echo ------create build.xml---------- call android create uitest-project -n %jar% -t 1 -p %reso% echo, echo ------ant build jar------------- call ant build 1>nul echo, echo ------push jar to device-------- adb push %jarLoction% /data/local/tmp/ echo, echo ------copy to current path------ copy %jarLoction% %dest% &pause