DEV Community

JL
JL

Posted on

Testing Spring Application (kotlin) with kotest, jacoco and mockk

Install Kotest

  1. In build.gradle.kts

Add a task for Test

tasks.withType<Test> {
    useJUnitPlatform()
}
Enter fullscreen mode Exit fullscreen mode

Under test dependencies section

Kotest on the JVM uses the JUnit Platform gradle plugin.
Kotest offers a Spring extension that allows you to test code that uses the Spring framework for dependency injection.

    testImplementation("io.kotest:kotest-runner-junit5-jvm:5.6.2")
    testImplementation("io.kotest.extensions:kotest-extensions-spring:1.1.3")
Enter fullscreen mode Exit fullscreen mode
  1. Installing the Kotest IntelliJ IDEA Plugin It makes things convenient when you want to run tests from editor via a click.

On IntelliJ, go to File > Settings... > Plugins. While on the Marketplace tab, search for "kotest," then select the first result and click on Install.

Ref: https://www.waldo.com/blog/kotest-get-started

Pick Testing Styles
It seems the creator of kotest tried the best to cater for all sorts of users.
These are just regular classes that extend one of the Kotest spec styles.

import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe

class StringCalculatorTest : FunSpec({

    test("empty string results in zero") {
        add("") shouldBe 0
    }
})

fun add(test: String) : Int {
    return 0
}
Enter fullscreen mode Exit fullscreen mode

Test Coverage
Add jacoco in plugins section in gradle.
Add following tasks and configs

/// Test Coverage
jacoco {
    toolVersion = "0.8.8"
    reportsDirectory.set(layout.buildDirectory.dir("jacoco"))
}

tasks.test {
    finalizedBy(tasks.jacocoTestReport, tasks.jacocoTestCoverageVerification)
}

tasks.jacocoTestReport {
    dependsOn(tasks.test)
    classDirectories.setFrom(
        sourceSets.main.get().output.asFileTree.matching {
            exclude("**/somepackage/**")
        }
    )
    reports {
        xml.required.set(true)
        html.required.set(true)
    }
}

tasks.jacocoTestCoverageVerification {
    //TODO update it to 0.9
    val minimumThresholdValue = "0.0".toBigDecimal()

    violationRules {
        classDirectories.setFrom(
            sourceSets.main.get().output.asFileTree.matching {
                exclude("**/somepackage/**")
            }
        )
        rule {
            limit {
                minimum = minimumThresholdValue
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Ref: https://www.baeldung.com/kotlin/kotest

Top comments (0)