Search code examples
gradlekotlinkotlintestparameterized-tests

Data Table tests in Kotlintest - advanced method names and spreading of test cases


I am using Kotlintest and data tables to test an application that uses Kotlin, SpringBoot and Gradle because the syntax is way more concise than ParameterizedJunitTests when you have complex data in your tables.

Is there a way to use the parameter names in the method-titles like there is for parameterized tests in JUnit? Moreover, all my test-executions are listed as one test, but I would like to have a row in my test results per data table row. I found neither of the two topics in the Documentation.

To make things clearer an example with Kotlintest:

class AdditionSpec : FunSpec() {
    init {

        test("x + y is sum") {
            table(
                    headers("x", "y", "sum"),
                    row(1, 1, 2),
                    row(50, 50, 100),
                    row(3, 1, 2)
            ).forAll { x, y, sum ->
                assertThat(x + y).isEqualTo(sum)
            }
        }
    }
}

and a corresponding example with JUnit:

@RunWith(Parameterized::class)
class AdditionTest {

    @ParameterizedTest(name = "adding {0} and {1} should result in {2}")
    @CsvSource("1,1,2", "50, 50, 100", "3, 1, 5")
    fun testAdd(x: Int, y: Int, sum: Int) {
        assertThat(x + y).isEqualTo(sum);
    }

}

With 1/3 failures: Kotlintest: Kotlintest gradle result with 1/3 failures Junit: Junit gradle result with 1/3 failures

Is there something similar to @ParameterizedTest(name = "adding {0} and {1} should result in {2}") in kotlintest when using data tables?


Solution

  • This is possible using the FreeSpec and the minus operator like this:

    class AdditionSpec : FreeSpec({
    
        "x + y is sum" - {
            listOf(
                row(1, 1, 2),
                row(50, 50, 100),
                row(3, 1, 2)
            ).map { (x: Int, y: Int, sum: Int) ->
                "$x + $y should result in $sum" {
                    (x + y) shouldBe sum
                }
            }
        }
    })
    

    This gives this output in Intellij: intellij test output

    See the documentation on this here