我正在使用ScalaCheck生成器alphaStr
生成字符串,但它们总是空回来。例如。第一个字符串上的以下测试失败。
class GenSpec extends FunSuite with GeneratorDrivenPropertyChecks with Matchers {
implicit val noShrink: Shrink[List[Char]] = Shrink.shrinkAny
test("alphaStr") {
forAll(Gen.alphaStr) { case str =>
println(str)
str.isEmpty shouldBe false
}
}
}
输出:
TestFailedException was thrown during property evaluation.
Message: true was not equal to false
Location: (GenSpec.scala:12)
Occurred when passed generated values (
arg0 = ""
)
ScalaTestFailureLocation: org.scalatest.prop.GeneratorDrivenPropertyChecks$class at (GeneratorDrivenPropertyChecks.scala:914)
org.scalatest.exceptions.GeneratorDrivenPropertyCheckFailedException: TestFailedException was thrown during property evaluation.
Message: true was not equal to false
Location: (GenSpec.scala:12)
Occurred when passed generated values (
arg0 = ""
)
我添加了noShrink
以确保基础的字符列表不会缩小。但它仍然失败。有谁知道为什么?
答案 0 :(得分:2)
在这种情况下,不确定缩小是否有效,alphaStr
不关心空值,但作为替代方法,您可以使用filter
和字符串长度:
Gen.alphaStr.filter(_.trim.length > 0)
答案 1 :(得分:1)
Gen.alphaStr.suchThat(_.nonEmpty)
完美工作,但有时它的 sample
可能会生成 None
(实际上当原始 alphaStr
生成器是空字符串时)。这有时是不可取的。
另一种方法是连接 Gen.alphaChar
和 Gen.alphaStr
的结果,如下所示:
Gen.zip(Gen.alphaChar, Gen.alphaStr).map(t => t._1 + t._2)