Published on

Getting Test Events to Log With Gradle's Kotlin DSL

Authors

I have found that porting standard Gradle to the Kotlin DSL is not always easy or sometimes even possible. The one configuration I could not work out until today I how to configure my build.gradle.kts to output test events.

When this is not configured when a test fails you get cryptic output that looks similar to the below:

> Task :test

com.example.util.extensions.number.NumberHelperKtTest > Int.asCurrencyString FAILED
 java.lang.AssertionError at NumberHelperKtTest.kt:16
 Caused by: java.lang.AssertionError at NumberHelperKtTest.kt:16

This tells you the line, but looking at just the console output it is not clear why it is failing without going to that line in the code.

With a standard none-Kotlin Gradle file it is easier to configure this. But I could not work out how to port this to the Kotlin DSL.

Today I came across this article. This is not for the Kotlin DSL but after a bit of fiddling I got it to work with the Kotlin DSL as below:

import org.gradle.api.tasks.testing.logging.TestExceptionFormat.*
import org.gradle.api.tasks.testing.logging.TestLogEvent.*

//...

tasks.withType<Test> {
    useJUnitPlatform()

    testLogging {
        events(FAILED, STANDARD_ERROR, SKIPPED)
        exceptionFormat = FULL
        showExceptions = true
        showCauses = true
        showStackTraces = true
    }
}

This now gives much clearer error messages when tests fail:

> Task :test

com.example.util.extensions.number.NumberHelperKtTest > Int.asCurrencyString FAILED
 java.lang.AssertionError: expected:<"R1,000,000.00"> but was:<"R1 000 000,00">
 at com.example.util.extensions.number.NumberHelperKtTest$1$1.invokeSuspend(NumberHelperKtTest.kt:16)
 at com.example.util.extensions.number.NumberHelperKtTest$1$1.invoke(NumberHelperKtTest.kt)

 Caused by:
 java.lang.AssertionError: expected:<"R1,000,000.00"> but was:<"R1 000 000,00">
 at com.example.util.extensions.number.NumberHelperKtTest$1$1.invokeSuspend(NumberHelperKtTest.kt:16)
 ... 1 more

I can now see exactly why the test is failing without going into the code.

In fact in this case, even going to the failing line in the test did not help as there was an issue with the locale when running the test in IntelliJ vs the terminal. The tests were passing in IntelliJ but not the terminal - my favourite types of test failures :/

This config works for the excellent kotest framework as well as for JUnit.