问题
The official scalacheck documentation gives the following example:
property("stringLength") = Prop.forAll { s: String =>
val len = s.length
(s+s).length == len+len
}
I read that this can also be written as:
val stringLength = Prop.forAll { s: String =>
val len = s.length
(s+s).length == len+len
}
How can I run the second form of test code? When I execute sbt test
, nothing happens with the second version.
回答1:
The problem is that the second version is simply declaring a val that holds a reference to the property in question but that isn't enough to get scalacheck to evaluate it. This style of declaring a property is useful for example if you want to compose a new property out of other basic properties. You can check it directly or to assign it the special property setter in order to get it to be evaluated as part of the test run:
val stringLength = Prop.forAll { s: String =>
val len = s.length
(s+s).length == len+len
}
// invoke directly:
stringLength.check
// alternatively, just declare it the usual way
property("stringLength") = stringLength
This isn't very useful by itself, the way it is meant to be used is perhaps something like this:
property("composite") = Prop.all(stringLength, prop2, prop3, ...)
来源:https://stackoverflow.com/questions/38284055/why-does-a-scalacheck-prop-value-not-get-evaluated