When working with Java microservices, ensuring high code coverage is crucial for maintaining code quality and reliability. However, if you are using Lombok to reduce boilerplate code, you might encounter a challenge: Lombok-generated methods can skew your code coverage reports, making it seem like you have less coverage than you actually do.
In this article, we’ll discuss how to configure Jacoco to ignore Lombok-generated methods and ensure your code coverage metrics accurately reflect your tested code.
Step 1: Configure Lombok
First, we need to configure Lombok to annotate the generated methods with @Generated
. This can be done by creating or updating a lombok.config
file at the root of your project.
Create or update lombok.config
:
# Disable Lombok for Jacoco
lombok.addLombokGeneratedAnnotation = true
This configuration tells Lombok to add the @Generated
annotation to the methods it generates, which can be used by Jacoco to exclude these methods from the coverage report.
Step 2: Update Jacoco Configuration
Next, we need to configure Jacoco to ignore methods annotated with @Generated
. This can be done by updating your build tool configuration.
For Maven
Update your pom.xml
:
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.7</version> <!-- Use the latest version -->
<configuration>
<excludes>
<exclude>**/*_$$_javassist_*</exclude>
<exclude>**/*.class</exclude> <!-- Exclude all generated class files -->
</excludes>
</configuration>
</plugin>
For Gradle
Update your build.gradle
:
jacocoTestReport {
afterEvaluate {
classDirectories.setFrom(files(classDirectories.files.collect {
fileTree(dir: it, exclude: ['**/*_$$_javassist_*', '**/*.class'])
}))
}
}
Step 3: Writing Tests for DTOs (Optional)
Even though Lombok handles the boilerplate code, it's still a good practice to write tests for your Data Transfer Objects (DTOs) to ensure they are correctly instantiated and that their getters and setters work as expected. Here’s an example using JUnit and AssertJ:
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
public class YourDtoTest {
@Test
public void testDtoGettersAndSetters() {
YourDto dto = new YourDto();
dto.setField1("value1");
dto.setField2(123);
assertThat(dto.getField1()).isEqualTo("value1");
assertThat(dto.getField2()).isEqualTo(123);
}
}
Conclusion
By configuring Lombok and Jacoco as shown above, you can ensure that your code coverage reports accurately reflect the code you need to test. This not only helps in maintaining high code quality but also provides a clearer picture of your project's test coverage.
With these configurations, you can focus on writing meaningful tests without worrying about the noise from Lombok-generated methods in your coverage reports.