1

我们有一个使用 Gradle/Android Studio 构建的 Android 应用程序,并且正在使用 JaCoCo 为我们的单元测试生成代码覆盖率报告;这很好用。我们也有兴趣为手动测试生成覆盖率报告;也就是说,显示在任意应用程序启动中覆盖了哪些代码。似乎 JaCoCo 的前任EclEmma能够做到这一点,但我无法以一种或另一种方式找到关于 JaCoCo 的任何确认(尽管由于缺乏话语,我开始假设这是不可能的)。

我曾尝试使用 Eclipse 中的 EclEmma 来获得一些东西,但最新版本因此错误而失败,而且我也无法立即让旧版本工作。

任何人都可以确认是否可以在使用 JaCoCo 启动任意应用程序时生成覆盖率数据?例如,运行应用程序,按下按钮,关闭应用程序并获取有关您按下的按钮执行了哪些代码的报告。如果没有,是否有其他工具可以做到这一点?

谢谢!

4

1 回答 1

6
apply plugin: 'jacoco'
def coverageSourceDirs = [
        '../app/src/main/java'
]

jacoco{
    toolVersion = "0.7.4.201502262128"
}

task jacocoTestReport(type: JacocoReport) {
    group = "Reporting"
    description = "Generate Jacoco coverage reports after running tests."
    reports {
        xml.enabled = true
        html.enabled = true
    }
    classDirectories = fileTree("enter code here"
            dir: './build/intermediates/classes/debug',
            excludes: ['**/R*.class',
                       '**/*$InjectAdapter.class',
                       '**/*$ModuleAdapter.class',
                       '**/*$ViewInjector*.class'
            ])
    sourceDirectories = files(coverageSourceDirs)
    executionData = files("$buildDir/outputs/code-coverage/connected/coverage.exec")
    doFirst {
        new File("$buildDir/intermediates/classes/").eachFileRecurse { file ->
            if (file.name.contains('$$')) {
                file.renameTo(file.path.replace('$$', '$'))
            }
        }
    }
}

// 这是用于报告的

 debug {
            testCoverageEnabled true
        }

// 这是离线的

将这些添加到 build.gradle 文件中。

将目录“资源”添加到 app>src>main

将 jacoco-agent.properties 文件添加到资源中。

将 destfile=/sdcard/coverage.exec 写入文件 jacoco-agent.properties

现在将此类添加到您的项目中。

public class jacoco {
    static void generateCoverageReport() {
        String TAG = "jacoco";
        // use reflection to call emma dump coverage method, to avoid
        // always statically compiling against emma jar
        String coverageFilePath = "/sdcard/coverage.exec";
        java.io.File coverageFile = new java.io.File(coverageFilePath);
        try {
            Class<?> emmaRTClass = Class.forName("com.vladium.emma.rt.RT");
            Method dumpCoverageMethod = emmaRTClass.getMethod("dumpCoverageData",
                    coverageFile.getClass(), boolean.class, boolean.class);

            dumpCoverageMethod.invoke(null, coverageFile, false, false);
            Log.e(TAG, "generateCoverageReport: ok");
        } catch (Exception  e) {
            new Throwable("Is emma jar on classpath?", e);
        }
    }
}

当您的应用程序处于 onDestroy 时调用该函数

jacoco.generateCoverageReport();

你可以运行你的应用程序。当测试结束时,您可以使用命令“adb pull /sdcard/coverage.exec yourapp/build/outputs/code-coverage/connected/coverage.exec”。

最后一个操作运行 gradle 任务定义上面有“jacocoTestReport”。

行。全部做完。在“yourapp/build/reports/jacoco/jacocoTestReport/html/”中打开 index.html。

于 2015-12-22T09:28:33.950 回答