如何确保 alphaStr 不会生成空字符串?
How do I ensure that alphaStr does not generate empty strings?
我正在使用 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
以确保底层字符列表不会缩小。但它仍然失败。有谁知道为什么?
不确定收缩在这种情况下是否有效,并且 alphaStr
不关心空值,但作为替代方案,您可以使用 filter
和字符串长度:
Gen.alphaStr.filter(_.trim.length > 0)
Gen.alphaStr.suchThat(_.nonEmpty)
完美运行,但有时它的 sample
可能会生成 None
(实际上当原始 alphaStr
生成器是空字符串时)。这有时是不可取的。
另一种方法是连接 Gen.alphaChar
和 Gen.alphaStr
的结果,如下所示:
Gen.zip(Gen.alphaChar, Gen.alphaStr).map(t => t._1 + t._2)
我正在使用 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
以确保底层字符列表不会缩小。但它仍然失败。有谁知道为什么?
不确定收缩在这种情况下是否有效,并且 alphaStr
不关心空值,但作为替代方案,您可以使用 filter
和字符串长度:
Gen.alphaStr.filter(_.trim.length > 0)
Gen.alphaStr.suchThat(_.nonEmpty)
完美运行,但有时它的 sample
可能会生成 None
(实际上当原始 alphaStr
生成器是空字符串时)。这有时是不可取的。
另一种方法是连接 Gen.alphaChar
和 Gen.alphaStr
的结果,如下所示:
Gen.zip(Gen.alphaChar, Gen.alphaStr).map(t => t._1 + t._2)