Android 自动化测试

方法一:Android Studio中双击(也可用gradlew命令执行)

Android 自动化测试_第1张图片

结果在:jt808lib/build/outputs/androidTest-results/connected/flavors/PLATFORM/TEST-wzd100 - 5.1-jt808lib-PLATFORM.xml中

方法二:ADB命令执行自动化测试

  1. 生成androidTest安装包:gradlew jt808lib:assembleAndroidTest 
  2. 安装测试包到目标设备:adb install 应用目录\jt808lib-Platform-debug-androidTest.apk
  3. 执行测试并输出结果到文件中:adb shell am instrument -w com.wissen.jt808lib.test/android.support.test.runner.AndroidJUnitRunner >>F:\androidtest.txt

参考Android官网:https://developer.android.google.cn/studio/test/command-line

 

    private static final String ADB_UNINSTALL_APP = "adb shell uninstall com.wissen.mapa";
    private static final String ADB_INSTALL_APP = "adb install -t -r ";
    private static final String ADB_RUN_ANDROID_TEST = "adb shell am instrument -w com.wissen.jt808lib.test/android.support.test.runner.AndroidJUnitRunner";

    /**
     * 运行AndroidTest
     *
     * @param path    APK相对路径
     * @param buildId BuildId
     */
    private void runAndroidTest(String path, String buildId) {
        //停止应用
        try {
            Process process = Runtime.getRuntime().exec(ADB_UNINSTALL_APP);
            process.waitFor();
            recordLog(buildId, "停止应用");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //执行安装
        try {
            Process process = Runtime.getRuntime().exec(ADB_INSTALL_APP + path);
            process.waitFor();
            recordLog(buildId, "安装应用");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //执行运行AndroidTest
        try {
            recordLog(buildId, "测试开始");
            Process process = Runtime.getRuntime().exec(ADB_RUN_ANDROID_TEST);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            //记录至文件中
            StringBuilder builder = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                if (StringUtils.isNotEmpty(line)) {
                    builder.append(line);
                    builder.append(System.getProperty("line.separator"));
                }
            }
            recordLog(buildId, builder.toString());
            process.waitFor();
            recordLog(buildId, "测试结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void recordLog(String buildId, String content) {
        try {
            String logFileName = ANDROID_TEST_RESULT_FILE_NAME + buildId + ".txt";
            FileOutputStream fileOutputStream = new FileOutputStream(logFileName, true);
            fileOutputStream.write(content.getBytes());
            fileOutputStream.write(System.lineSeparator().getBytes());
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

你可能感兴趣的:(Android)