Android 项目进行了模块化,手工运行完测试用例之后,jacoco 只统计一个模块下面的代码覆盖,其它模块的统计出来的数据都是为 0。
build.gradle:
apply plugin: "jacoco"
def coverageSourceDirs = ['../app/src/']
task jacocoTestReport(type: JacocoReport) {
group = "Reporting"
description = "Generate Jacoco coverage reports after running tests."
reports {
xml.enabled true
html.enabled true
}
classDirectories = fileTree(
dir: './build/intermediates/classes/product/debug',
excludes: ['/R*.class',
'/$InjectAdapter.class',
'/$ModuleAdapter.class',
'*/$ViewInjector*.class'
])
sourceDirectories = files(coverageSourceDirs)
executionData = files("$buildDir/outputs/code-coverage/connected/coverage.ec")
doFirst {
new File("$buildDir/intermediates/classes/").eachFileRecurse { file ->
if (file.name.contains('$$')) {
file.renameTo(file.path.replace('$$', '$'))
}
}
}
}
统计代码如下:
OnCreate:
String SDCARD_PATH = Environment.getExternalStorageDirectory().getPath();
String DEFAULT_COVERAGE_FILE_PATH = SDCARD_PATH + "/coverage.ec";
File file = new File(DEFAULT_COVERAGE_FILE_PATH);
if (! file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
OnDestroy:
public void generateCoverageReport() {
String SDCARD_PATH = Environment.getExternalStorageDirectory().getPath();
String DEFAULT_COVERAGE_FILE_PATH = SDCARD_PATH + "/coverage.ec";
Log.d("generateCoverageReport", "generateCoverageReport():" + DEFAULT_COVERAGE_FILE_PATH);
OutputStream out = null;
try {
out = new FileOutputStream(DEFAULT_COVERAGE_FILE_PATH, false);
Object agent = Class.forName("org.jacoco.agent.rt.RT").getMethod("getAgent").invoke(null);
out.write((byte[]) agent.getClass().getMethod("getExecutionData", boolean.class).invoke(agent, false));
} catch (Exception e) {
Log.d("generateCoverageReport", e.toString(), e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
覆盖数据都有,只是 HTML 文件显示代码都未运行,可以确认 MainActivity 是有运行的,但并未统计出来。求大神解答