原文地址https://blog.csdn.net/wuxuehong0306/article/details/50698411
原理:
用Java调用Windows Command命令 -> Windows Command调用安卓SDK的ADB命令 -> ADB命令调用monkey。
优点:
通过Java代码来实现monkey的功能,可以把脚本部署到持续监控平台完成,无需人工运行。代码中将运行时的log保存到本地,并解析log,一旦出现了App崩溃的异常,测试就报错,并打印异常信息。
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class AndroidPerformance {
public static void RunMonkey(String PackageName, String count) {
Monkey("", PackageName, "", count, "C:\\monkey\\" + GeneralMethods.getTimeStamp() + ".txt");
}
private static void Monkey(String DevicesName, String PackageName, String sleepTime, String count, String path) {
Runtime runtime1 = Runtime.getRuntime();
String cmd = "adb " + DevicesName + " shell monkey -p " + PackageName + " --throttle 150 " + count + " > " + path;
try {
String[] args = new String[] { "cmd", "/c", cmd };
Process pro1 = runtime1.exec(args);
if (pro1.waitFor() != 0) {
System.err.println("exit value:" + pro1.exitValue());
throw new RuntimeException("shell monkey failed!");
}
Thread.sleep(5000);
} catch (Exception e) {
throw new RuntimeException("error Message:" + e.getMessage());
}
String log = checkLog(path);
if (log.contains("crash") || log.contains("NullPointerException"))
throw new RuntimeException(log);
}
@SuppressWarnings("resource")
private static String checkLog(String path) {
String log = "";
try {
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuffer sb = new StringBuffer();
String str = "";
while ((str = br.readLine()) != null) {
if (str.contains("at android."))
GeneralMethods.log(str, 2);
sb.append(str);
}
sb.deleteCharAt(sb.length() - 1);
log = sb.toString().split("System appears to have ")[1];
} catch (Exception e) {
}
return log;
}
测试方法:
@Test
public void test010Navigation() {
up.log(">========================<");
up.log("开始测试:Monkey随机事件测试");
int times = 50000;
System.out.println(("随机事件次数:" + times));
AndroidPerformance.RunMonkey("", String.valueOf(times));
}