Thursday, October 22, 2020

Gradle: Exclude SpringBoot Application Class from Jacoco Coverage

 

Jacoco plugin is a must if you care about not just writing random unit tests, but to ensure you have the right coverage for your code base. The plugin also comes with a report that shows the coverage at package level.

One thing that has been bothering me with SpringBoot apps I work with is the low number that always appears for the main SpringBoot Application class. This is a boiler plate class with a simple main method to launch the SpringApplication:

@SpringBootApplication
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}

Almost in every application we won't need to add any other additional logic to this method which makes it kind of dumb to create a test just to cover this class and main method. Best thing is to exclude it from our coverage using this format (in this case for Gradle):

jacocoTestReport {

    afterEvaluate {
        classDirectories.from = files(classDirectories.files.collect {
            fileTree(dir: it, exclude: 'com/mycom/shoppingcart/ServiceShoppingCartApplication.class')
        })
    }
}