我已经使用Lists
创建了Gen.oneOf(List[T])
以及相应类型的一些外部Scalacheck生成器。我认为返回一个空值的占位符偶尔会有用。目前列表已填充。我该怎么办呢?我是否尝试将空类型附加到列表的末尾?如果是这样我该怎么办呢?如果没有,我怎么能让我的生成器添加一个空值。这看起来很简单,但我现在无法搞清楚。
import org.scalatest.FlatSpec
import org.scalacheck.Gen
import org.scalacheck.Prop.exists
import org.scalatest.prop.PropertyChecks
class EventFieldGeneratorTest extends FlatSpec with PropertyChecks {
behavior of "Gen.option"
it should "occasionally return None" in {
val colors = Gen.oneOf("Blue", "Red", "Green", "Yellow")
val opt = Gen.option(colors)
val list = Gen.listOfN(20, opt)
val p1 = exists(list)(_ == None)
p1.check
}
}
有人可以解释为什么我的测试放弃了吗?
Testing started at 10:31 AM ... ! Gave up after only 0 passed tests. 501 tests were discarded.
Process finished with exit code 0
如何将其标记为ScalaTest的失败结果?我使用Flatspec
是不是一个坏主意?
也许我应该使用check
以外的其他东西......
这是我用来对其进行排序的文档。在Scalatest页面上:
http://www.scalatest.org/user_guide/writing_scalacheck_style_properties
答案 0 :(得分:1)
我不认为尝试使用带有可选值的列表存在任何缺陷。您只是遇到了一些问题,这些问题会给您带来麻烦。
令人困惑,但如果您正在使用Scalatest框架,则需要使用Scalatest基础结构来使用Scalacheck。因此,您需要使用Scalatest匹配器,并编写Scalatest风格的属性(使用它forAll
),但您仍然会直接使用Scalacheck的生成器。
由于某种原因,列表与Option
类型之间的类型推断会给您带来麻烦。如果您使用shouldBe
匹配器,
x shouldBe(None)
您将从Scalatest获得相关的运行时错误:
[info] - should occasionally return None *** FAILED ***
[info] TestFailedException was thrown during property evaluation.
[info] Message: List() was not equal to None
[info] Location: (GenTest.scala:13)
[info] Occurred when passed generated values (
[info] arg0 = List() // 5 shrinks
[info] )
[info] Run completed in 1 second, 621 milliseconds.
[info] Total number of tests run: 1
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 0, failed 1, canceled 0, ignored 0, pending 0
您不应该将列表与Option
类型匹配。你需要与Scalatest"容器匹配"匹配器should contain
import org.scalatest.FlatSpec
import org.scalatest.Matchers
import org.scalacheck.Gen
import org.scalatest.prop.PropertyChecks
class EventFieldGeneratorTest extends FlatSpec with Matchers with PropertyChecks {
behavior of "Gen.option"
it should "occasionally return None" in {
val colors = Gen.oneOf("Blue","Red","Green","Yellow")
val opt = Gen.option(colors)
val list = Gen.listOfN(20,opt)
forAll(list) { (xs: List[Option[String]]) =>
xs should contain (None)
}
}
}
这为您提供了成功的财产检查:
[info] EventFieldGeneratorTest:
[info] Gen.option
[info] - should occasionally return None
[info] ScalaTest
[info] Run completed in 1 second, 9 milliseconds.
[info] Total number of tests run: 1
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 1, failed 0, canceled 0, ignored 0, pending 0
[info] All tests passed.
[info] Passed: Total 1, Failed 0, Errors 0, Passed 1
有关Scalatest匹配器的更多信息