javaunit-testingantjacoco

Jacoco @Generated annotation is not excluding class with methods having anonymous class


I am using following this article to exclude any custom class where I dont want to write test cases https://www.baeldung.com/jacoco-report-exclude annotation to exclude class from jacoco coverage. I found jacoco looks for Generated word in annotation and exclude the annotation class. https://github.com/jacoco/jacoco/pull/822/files

So went ahead and created following annoation:-

@Target({ElementType.TYPE,ElementType.METHOD})
public @interface ExcludeFromJacocoGeneratedReport {
}

I wanted to exclude following class from coverage report

@ExcludeFromJacocoGeneratedReport
class UserRepoImpl {

public long getCountById(long userId){

 UserFetcher fether =
 // this shows up as red in jacoco report coverage, ideally it shouldn't as i have already excluded the whole class using ExcludeFromJacocoGeneratedReport annotation.
new UserFetcher  public void init(long userId){
         //initialise user 
    }
}; 
}


public void updateUser(User user){
//update the user
}
}

Annoymous class should automatically get excluded from jacoco coverage report but its not happening and showing 0% coverage.


Solution

  • I found the answer, here is what you can try :-

    As ElementType.TYPE_USE in your annotation (this will work for jdk 8,+)

    @Target({ElementType.TYPE,ElementType.METHOD, ElementType.TYPE_USE})
    public @interface ExcludeFromJacocoGeneratedReport {
    } 
    

    and tried this, but it didn't work, I don't know why its not excluding anonymous class.

    @ExcludeFromJacocoGeneratedReport
    class UserRepoImpl {
    
    public long getCountById(long userId){
    
     UserFetcher fether =
    new @ExcludeFromJacocoGeneratedReport UserFetcher  public void init(long userId){
             //initialise user 
        }
    }; 
    }
    
    
    public void updateUser(User user){
    //update the user
    }
    }
    
    
    

    To exclude anonymous class I had to manually exclude using *$*.* in my build.xml as

    <exclude name = "**/**/*$*.*"/>
    

    Run the report again and you are good to go.