Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 640
peach Avatar asked Sep 02 '25 16:09

peach


1 Answers

You can reverse nesting. Instead of having table within test, simply nest test within table.

class AdditionSpec : FunSpec() {
    init {
        context("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 ->
                test("$x + $y should be $sum") {
                    x + y shouldBe sum
                }
            }
        }
    }
}
like image 86
Frank Neblung Avatar answered Sep 04 '25 07:09

Frank Neblung