Exclude unit tests from code coverage analysis with JaCoCo

Viewed 1529

I am using JaCoCo with Gradle. Is there any way to exclude some unit tests from code coverage analysis of tested code? (Note that I do not mean hiding unit tests or some classes from the coverage report, which was discussed in, e.g., Filter JaCoCo coverage reports with Gradle).

I have some test which is for a kind of consistency check of a necessary condition, in other words, the test is weak; the test is expected to most likely pass in any way. If it fails the tested code definitely has a certain type of a bug, but even if it passes it can't guarantee that the code is completely right (this should be checked by another stronger test, which is taken into account for code coverage). So surely I would like to run this unit test in gradle test, but do not like to include it for code coverage analysis of the tested code.

1 Answers

You can use different Gradle tasks for different types of tests. For example

src/main/java/Example.java

class Example {
    void weak() {
        System.out.println("weak");
    }

    void strong() {
        System.out.println("strong");
    }
}

src/test/java/StrongTest.java

import org.junit.Test;

public class StrongTest {
    @Test
    public final void test() {
        new Example().strong();
    }
}

src/test/java/WeakTest.java

import org.junit.Test;

public class WeakTest {
    @Test
    public void test() {
        new Example().weak();
    }
}

and finally build.gradle

apply plugin: 'java'
apply plugin: 'jacoco'

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'junit:junit:4.13'
}

test {
    exclude 'WeakTest.class'
}

task weakTest(type: Test) {
    include 'WeakTest.class'
}

check.dependsOn weakTest

Default test task will execute everything except WeakTest and will use JaCoCo to collect execution information into build/jacoco/test.exec.

Custom weakTest task will execute only WeakTest and will use JaCoCo to collect execution information into build/jacoco/weakTest.exec.

Default jacocoTestReport will use information from build/jacoco/test.exec for generation of HTML report.

So that execution of

gradle clean build jacocoTestReport

using Gradle 6.2.1 will generate the following report in directory build/reports/jacoco/test/html/ that doesn't contain information about execution of WeakTest

report

Related