【问题标题】:Data Table tests in Kotlintest - advanced method names and spreading of test casesKotlintest 中的数据表测试 - 高级方法名称和测试用例的传播
【发布时间】:2019-10-09 11:26:20
【问题描述】:

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

有没有办法像parameterized tests in 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中是否有类似@ParameterizedTest(name = "adding {0} and {1} should result in {2}")的东西?

【问题讨论】:

    标签: gradle kotlin kotlintest parameterized-tests


    【解决方案1】:

    您可以反向嵌套。不要将table 放在test 中,而是将test 嵌套在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
                    }
                }
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      这可以像这样使用 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 中给出了以下输出:

      请参阅here 上的文档

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-10
        • 2016-09-12
        • 2018-07-23
        • 2014-09-14
        • 2018-04-04
        • 2021-02-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多