Clement
Clement

Reputation: 4811

Is there an easy way to exclude classes from test coverage using Java Annotations in Spring Boot?

I have a (gradle + kotlin) spring boot project with several DTOs, configuration classes, constants etc. that I don't want to be analyzed during test coverage analysis.

Is there a convenient Java notation that I can use?

Upvotes: 2

Views: 2658

Answers (2)

Clement
Clement

Reputation: 4811

This is what ended up working for me. Had to write some custom custom filtering logic in a very hacky sort of way, but it did the job.

Upvoting @Min Hyoung Hong's answer for leading me down the right track.

build.gradle.kts

tasks {
    withType<KotlinCompile<KotlinJvmOptions>> {
        kotlinOptions.freeCompilerArgs = listOf("-Xjsr305=strict")
        kotlinOptions.jvmTarget = "1.8"
    }

    withType<JacocoReport> {
        reports {
            xml.isEnabled = false
            csv.isEnabled = false
            html.destination = file("$buildDir/jacocoHtml")
        }

        afterEvaluate {
            val filesToAvoidForCoverage = listOf(
                    "/dto",
                    "/config",
                    "MyApplicationKt.class"
            )
            val filesToCover = mutableListOf<String>()
            File("build/classes/kotlin/main/app/example/core/")
                    .walkTopDown()
                    .mapNotNull { file ->
                        var match = false
                        filesToAvoidForCoverage.forEach {
                            if (file.absolutePath.contains(it)) {
                                match = true
                            }
                        }
                        return@mapNotNull if (!match) {
                            file.absolutePath
                        } else {
                            null
                        }
                    }
                    .filter { it.contains(".class") }
                    .toCollection(filesToCover)

            classDirectories = files(filesToCover)
        }
    }
}

Upvotes: 0

Min Hyoung Hong
Min Hyoung Hong

Reputation: 1202

You said that you are using kotlin and gradle. So I assume that you are using jacoco for test coverage.

This is one of the jacoco coverage excludes example.

jacocoTestReport {
    afterEvaluate {
        classDirectories = files(classDirectories.files.collect {
            fileTree(dir: it,
                    exclude: ['**/*Application**'])
        })
    }
}

Upvotes: 2

Related Questions