Java实现安卓压力测试

原文地址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));

    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值