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

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("https://stackoverflow.com/"),
                    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() {}
}

Leave a Comment