我想测试我的功能并使用ScalaCheck。
属性测试如下所示:
object WindowsSpec extends Properties("Windows") {
val pathsGen = Gen.frequency(
(3, "C:\\Windows\\DigitalLocker"),
(2, "C:\\Temp"),
(3, "Invalid folder"),
(1, "C:\\Program Files\\Internet Explorer"),
(4, "C:\\Program Files\\Windows Defender Advanced Threat Protection"),
(1, "C:\\Program Files\\Windows Photo Viewer")
)
val pathsGenContainer = Gen.containerOf[List,String](pathsGen)
property("validPaths") = forAll(pathsGenContainer) { a: List[String] =>
println(a)
Windows.arePathsValid(a).value.length > 0
}
}
为什么我会得到一个空列表?
我尝试在shell中查找,如果生成器工作:
scala> :paste
// Entering paste mode (ctrl-D to finish)
val pathsGen = Gen.frequency(
(3, "C:\\Windows\\DigitalLocker"),
(2, "C:\\Temp"),
(3, "Invalid folder"),
(1, "C:\\Program Files\\Internet Explorer"),
(4, "C:\\Program Files\\Windows Defender Advanced Threat Protection"),
(1, "C:\\Program Files\\Windows Photo Viewer")
)
val pathsGenContainer = Gen.containerOf[List,String](pathsGen)
// Exiting paste mode, now interpreting.
pathsGen: org.scalacheck.Gen[String] = org.scalacheck.Gen$$anon$1@6cb26245
pathsGenContainer: org.scalacheck.Gen[List[String]] = org.scalacheck.Gen$$anon$1@5335e968
scala> pathsGen
pathsGen pathsGenContainer
scala> pathsGen.sample
res26: Option[String] = Some(C:\Program Files\Internet Explorer)
scala> pathsGen
val pathsGen: org.scalacheck.Gen[String]
scala> pathsGenContainer.sample
res27: Option[List[String]] = Some(List(C:\Temp, C:\Temp, C:\Program Files\Windows Defender Advanced Threat Protection, Invalid folder, C:\Program Files\Internet Explorer, C:\Program Files\Internet Explorer, C:\Temp, C:\Temp, C:\Program Files\Windows Photo Viewer, Invalid folder, C:\Program Files\Windows Defender Advanced Threat Protection, C:\Program Files\Windows Defender Advanced Threat Protection, C:\Windows\DigitalLocker, Invalid folder, C:\Program Files\Windows Photo Viewer, C:\Program Files\Windows Defender Advanced Threat Protection, C:\Temp, C:\Program Files\Internet Explorer, C:\Temp, C:\Program Files\Windows Defender Advanced Threat Protection, C:\Program Files\Windows Photo Viewer, Invalid folder, Invalid folder, C:\Windows\DigitalLocker, C:\Program...
如您所见,发电机会产生一些输入 我做错了什么?
答案 0 :(得分:1)
pathsGenContainer
可以简化为Gen.listOf(pathsGen)
,所以我会参考。它生成一个空列表是完全合理的。事实上,它是可取的,因为空列表是边缘情况,因此更有可能触发错误。如果您需要非空列表生成器,则可以将Gen.nonEmptyListOf
或Gen.nonEmptyContainerOf
用于其他集合。
forAll
和sample
之间有什么不同?您发现在REPL中调用sample
通常会生成非空列表,但运行forAll
测试始终会生成一个空列表。这就是区别:
forAll
:当框架运行测试时,它会使用不同的属性运行多次,其中一个属性size
在可配置的范围内变化(默认为[0 - 100] )。 listOf
生成器具有大小感知功能,并会在每次测试时获取此属性。由于0是最小尺寸,因此总是进行测试并得到一个空列表。sample
:您只需手动调用几次,而且您不会传递任何属性。因此,生成器只生成一个随机列表。如果你一直打电话给sample
,最终你将获得一个空列表,但它不是确定性的。请注意,100%随机数据对测试没有用,我们总是希望确保检查边缘情况。