3

我正在使用 Kotlintest 和数据表来测试使用 Kotlin、SpringBoot 和 Gradle 的应用程序,因为当表中有复杂数据时,语法比 ParameterizedJunitTests 更简洁。

有没有办法像JUnit 中的参数化测试一样使用方法标题中的参数名称?此外,我所有的测试执行都被列为一个测试,但我希望在每个数据表行的测试结果中都有一行。我在Documentation中都没有找到这两个主题。

为了让事情更清楚,举个 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)
            }
        }
    }
}

和 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);
    }

}

有 1/3 失败: Kotlintest: Kotlintest gradle 结果有 1/3 失败 Junit: Junit gradle 结果有 1/3 失败

使用数据表时是否有类似于@ParameterizedTest(name = "adding {0} and {1} should result in {2}")kotlintest 的内容?

4

2 回答 2

2

您可以反向嵌套。而不是有tablewithin test,而是简单地嵌套test在inside 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
                }
            }
        }
    }
}
于 2019-12-09T07:20:48.540 回答
1

这可以使用 FreeSpec 和减号运算符,如下所示:

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
            }
        }
    }
})

这在 Intellij 中给出了以下输出: Intellij 测试输出

请参阅此处的文档

于 2019-12-08T16:48:44.393 回答