概要
プロジェクト内に複数のモジュールが存在する時、アプリケーションのメインとなるモジュールでテストを動かすと、JaCoCo のカバレッジ計測ではメインのモジュールにあるクラスのみが計測対象となります。特に、以下のようなコードがビルドスクリプトにある場合は、依存しているライブラリモジュールのクラスのカバレッジが計測できません。
app/build.gradle
task jacocoTestReport(type: JacocoReport, dependsOn: ['testDebugUnitTest']) {
reports {
xml.enabled true
csv.enabled false
xml.destination "${buildDir}/reports/jacoco/test/jacocoTestReport.xml"
html.destination "${buildDir}/reports/coverage"
classDirectories = fileTree(
dir: "${buildDir}/intermediates/classes/debug",
exclude: ['**/R.class', '**/R$*.class'])
}
// ...
}
依存モジュールのクラスも計測対象に含めるには
肝心なのは、カバレッジ計測のレポートを生成するタスクの宣言にある report の最後、classDirectories
の部分です。
ここでカバレッジの計測対象となるクラスがどこにあるかを指定していますが、上述のような記述では、メインとなるモジュールのクラスしか含まれません。
classDirectories
とある通り、複数のファイルパスを放り込むことができるので、以下のように書き換えてみます。
app/build.gradle
task jacocoTestReport(type: JacocoReport, dependsOn: ['testDebugUnitTest']) {
reports {
xml.enabled true
csv.enabled false
xml.destination "${buildDir}/reports/jacoco/test/jacocoTestReport.xml"
html.destination "${buildDir}/reports/coverage"
classDirectories = files(
fileTree(
dir: "${buildDir}/intermediates/classes/debug",
exclude: ['**/R.class', '**/R$*.class']),
fileTree(
dir: "${rootDir}/depModule/build/intermediates/classes/release",
exclude: ['**/R.class', '**/R$*.class']))
}
// ...
}
files()
は複数のファイルパスを渡すことができ、fileTree()
の戻り値も指定できます。ということで、fileTree()
で指定したパスをfiles()
に渡してその戻り値をclassDirectories
に投げ込んでやることで、依存モジュールのクラスもカバレッジの計測対象になります。