Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

474
Views
Test Lombok's @UtilityClass auto-generated code

I have a class that's annotated with @UtilityClass like this

@UtilityClass
public class myUtilClass {
...
}

JaCoCo doesn't give me full coverage for this class because of the auto-generated code created by the annotation @UtilityClass . Ideally, I do not want to change any config files to ignore auto-gen code. How can this code be tested?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

The only "coverable" code that is generated by @UtilityClass is in the constructor:

private MyUtilClass() {
    throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
}

As this is a private constructor that never should be called, you cannot test it regularly.

If you really want to call it, you can do it with some ugly reflective code:

Constructor<MyUtilClass> constructor;
constructor = MyUtilClass.class.getDeclaredConstructor();
constructor.setAccessible(true);
constructor.newInstance();

But you should not do this just for the sake of coverage. Having a high coverage is generally a good idea, but not if you have to sacrifice good testing standards.

I suggest you advice JaCoCo to ignore Lombok's code by adding this line to your lombok.config file:

lombok.addLombokGeneratedAnnotation = true

You don't have to configure this for your whole project. If you put this file only into the package of MyUtilClass, JaCoCo will only ignore generated code in this package.

over 4 years ago · Santiago Trujillo Report

0

Just write this unit test to ensure your class cannot be instantiated because of @UtilityClass annotation. Then, coverage will be OK.

@Test
  void test_cannot_instantiate() {
    assertThrows(InvocationTargetException.class, () -> {
      var constructor = YOUR_CLASS_NAME.class.getDeclaredConstructor();
      assertTrue(Modifier.isPrivate(constructor.getModifiers()));
      constructor.setAccessible(true);
      constructor.newInstance();
    });
  }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!