我试图在ScalaCheck中生成可选参数,但没有成功.
似乎没有直接机制.Gen.containerOf[Option, Thing](thingGenerator)
失败,因为它无法找到隐含的Buildable[Thing, Option]
.
我试过了
for {
thing <- Gen.listOfN[Thing](1, thingGenerator)
} yield thing.headOption
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为listOfN
产生一个总长度为N的列表.结果我总是得到一个Some[Thing]
.类似地,listOf1
不起作用,因为(a)它不产生空列表,而且(b)它效率低,因为我不能设置元素数量的最大限制.
我怎样才能生成Option[Thing]
包含Nones的内容?
编辑:我找到了解决方案,但它并不简洁.有比这更好的方法吗?
for {
thing <- for {
qty <- Gen.choose(0,1)
things <- Gen.listOfN[Thing](qty, thingGenerator)
} yield things.headOption
} yield thing
Run Code Online (Sandbox Code Playgroud)
编辑2:我将此概括为
def optional[T](g: Gen[T]) =
for (qty <- Gen.choose(0, 1); xs <- Gen.listOfN[T](qty, g)) yield xs.headOption
Run Code Online (Sandbox Code Playgroud)
所以我不必多次写它.但肯定这已经在图书馆了,我只是错过了它?
您可以使用pick
在Some和None生成器之间随机选择:
val someThing = thingGenerator.map( Some.apply )
val noThing = Gen.value( None:Option[Thing] )
val optThing = Gen.oneOf( someThing, noThing )
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2542 次 |
最近记录: |