Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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() {} } 
like image 966
Don Rhummy Avatar asked Dec 15 '17 01:12

Don Rhummy


People also ask

How do you exclude methods in JaCoCo code coverage?

Excluding With Custom Annotation Starting from JaCoCo 0.8. 2, we can exclude classes and methods by annotating them with a custom annotation with the following properties: The name of the annotation should include Generated. The retention policy of annotation should be runtime or class.

How do you exclude a class from code coverage?

The easiest way to exclude code from code coverage analysis is to use ExcludeFromCodeCoverage attribute. This attribute tells tooling that class or some of its members are not planned to be covered with tests. EditFormModel class shown above can be left out from code coverage by simply adding the attribute.

How do you exclude getters and setters from code coverage?

With the cobertura-maven-plugin setters and getters can be excluded from code coverage using the ignoreTrivial option.


2 Answers

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() {} } 
like image 60
Mohamed Anees A Avatar answered Sep 23 '22 11:09

Mohamed Anees A


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

like image 42
Ajinkya Avatar answered Sep 20 '22 11:09

Ajinkya