How would I add an annotation to exclude a method from a jacoco code coverage report?

2022-08-31 16:58:59

I have some code in Java that I want to exclude from code coverage. How would I do this? I want to be able to add an annotation. Is there a way to configure or extend jacoco (as used in gradle) to use this?

Example:

public class Something
{
    @ExcludeFromCodeCoverage
    public void someMethod() {}
}

答案 1

Since there are no direct answers to this, did a bit of research and came across this PR.

https://github.com/jacoco/jacoco/pull/822/files

  private static boolean matches(final String annotation) {
    final String name = annotation
            .substring(Math.max(annotation.lastIndexOf('/'),
                    annotation.lastIndexOf('$')) + 1);
    return name.contains("Generated")
  }

You can create any annotation with name containing "Generated". I've created the following in my codebase to exclude methods from being included in Jacoco report.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ExcludeFromJacocoGeneratedReport {}

Use this annotation in your methods to exempt it from coverage as below.

public class Something
{
    @ExcludeFromJacocoGeneratedReport
    public void someMethod() {}
}

答案 2

The new feature has been added in the 0.8.2 release of JaCoCo which filters out the classes and methods annotated with @Generated. For details please see the documentation below:

Classes and methods annotated with annotation whose retention policy is runtime or class and whose simple name is Generated are filtered out during generation of report (GitHub #731).

JaCoCo 0.8.2 Release Notes


推荐