似乎Gradle JaCoCo Plugin增强了testNG任务,使其执行使用JaCoCo Java agent,但忘记更新jacocoTestReport任务,使得该任务不使用testNG任务的执行结果.不知道这是一个错误还是故意的,但下面提供了解决方案。
证明这一点
文件src/main/java/Example.java:
public class Example {
public void junit() {
System.out.println("JUnit");
}
public void testng() {
System.out.println("TestNG");
}
}
文件src/test/java/ExampleJUnitTest.java:
import org.junit.Test;
public class ExampleJUnitTest {
@Test
public void test() {
new Example().junit();
}
}
文件src/test/java/ExampleTestNGTest.java:
import org.testng.annotations.Test;
public class ExampleTestNGTest {
@Test
public void test() {
new Example().testng();
}
}
文件build.gradle:
apply plugin: 'java'
apply plugin: 'jacoco'
repositories {
mavenCentral()
}
dependencies {
testCompile 'org.testng:testng:6.8.8'
testCompile 'junit:junit:4.12'
}
task testNG(type: Test) {
useTestNG()
}
test {
dependsOn testNG
}
gradle clean test jacocoTestReport -d 执行后你会在日志中看到
java ... -javaagent:.../jacocoagent.jar=destfile=build/jacoco/testNG.exec ...
...
java ... -javaagent:.../jacocoagent.jar=destfile=build/jacoco/test.exec ...
该目录 build/jacoco 包含两个文件 - testNG.exec 和 test.exec,分别用于 testNG 和 test 任务。而 JaCoCo 报告仅显示 test 任务对 JUnit 的执行。
解决这个问题
指示任务testNG将执行数据写入与test相同的文件:
task testNG(type: Test) {
useTestNG()
jacoco {
destinationFile = file("$buildDir/jacoco/test.exec")
}
}
指示任务jacocoTestReport 也使用testNG.exec 文件:
jacocoTestReport {
executionData testNG
}
我假设对于多模块项目的情况,尤其是您的情况,我假设应该这样做,因为您的多模块项目设置的Minimal, Complete, and Verifiable example 没有提供。