如何从TableDrivenPropertyChecks中获得最新的/sbt报告标签案例



我是scalatest的新手,有点迷失在巨大的不一致的混乱特性中

我正在尝试编写参数化测试。这样做的方法似乎是通过TableDrivenPropertyChecks

我设法让它工作的测试,如:

import org.scalatest.funspec.AnyFunSpec
import org.scalatest.prop.TableDrivenPropertyChecks
class MyTest extends AnyFunSpec with TableDrivenPropertyChecks {
describe("the test") {
val cases = Table(
("label", "a", "b"),
("case 2 > 1", 1, 2),
("case 4 > 3", 3, 4),
)
it("should...") {
forAll(cases) { (name: String, a: Int, b: Int) =>
assert(b > a)
}
}
}
}

很好,但是当我在sbt下运行时,我只看到:

[info] MyTest:
[info] the test
[info] - should...

如果我注入一个坏的case到表中,我可以看到测试失败,这样我就知道它们都被测试了。

我想让测试运行器为表中的每个case报告一些东西。

我看到过类似的例子,例如:https://blog.knoldus.com/table-driven-testing-in-scala/

import org.scalatest.FreeSpec
import org.scalatest._
import org.scalatest.prop.TableDrivenPropertyChecks
class OrderValidationTableDrivenSpec extends FreeSpec with TableDrivenPropertyChecks with Matchers {
"Order Validation" - {
"should validate and return false if" - {
val orders = Table(
("statement"                          , "order")
, ("price is negative"                , Order(quantity = 10, price = -2))
, ("quantity is negative"             , Order(quantity = -10, price = 2))
, ("price and quantity are negative"  , Order(quantity = -10, price = -2))
)
forAll(orders) {(statement, invalidOrder) =>
s"$statement" in {
OrderValidation.validateOrder(invalidOrder) shouldBe false
}
}
}
}
}

但是如果我在测试中尝试这样做:

import org.scalatest.funspec.AnyFunSpec
import org.scalatest.prop.TableDrivenPropertyChecks
class MyTest extends AnyFunSpec with TableDrivenPropertyChecks {
describe("the test") {
val cases = Table(
("label", "a", "b"),
("case 2 > 1", 1, 2),
("case 3 > 4", 3, 4),
)
it("should...") {
forAll(cases) { (label: String, a: Int, b: Int) =>
s"$label" in {
assert(b > a)
}
}
}
}
}

…我从s"$label" in {部分得到错误:value in is not a member of String

我如何让我的TableDrivenPropertyChecks报告表中的每个情况?

ScalaTest的一个很酷的特性是test不是一个方法,所以你可以在循环中定义测试:

Table(
("a", "b"),
(1, 2),
(3, 4)
).forEvery({ (a: Int, b: Int) => {
it(s"should pass if $b is greater then $a") {
assert(b > a)
}
}})

或者即使不使用Table,也可以使用任何集合:

Seq(
(1, 2),
(3, 4)
).foreach {
case (a: Int, b: Int) =>
it(s"should pass if $b is greater then $a") {
assert(b > a)
}
}

这样,每次循环迭代你都会得到一个测试,所以所有的用例都将独立执行,而在单个测试中循环的情况下,它将在第一个失败的断言时失败,并且不会检查剩余的用例。

最新更新