我正在尝试使用ScalaCheck,并且无法弄清楚如何在ScalaTest用户手册上构建第一个示例。我非常确定以下内容需要先进行一些导入并包含在从某个库类扩展的类中。 page in the user's manual说"混合" PropertyChecks
,但它没有给出一个合适的类的示例,以便将其混合到:
forAll { (n: Int, d: Int) =>
whenever (d != 0 && d != Integer.MIN_VALUE
&& n != Integer.MIN_VALUE) {
val f = new Fraction(n, d)
if (n < 0 && d < 0 || n > 0 && d > 0)
f.numer should be > 0
else if (n != 0)
f.numer should be < 0
else
f.numer should be === 0
f.denom should be > 0
}
}
我一直尝试各种组合,但到目前为止我得到的最好结果是这样的编译错误:
[info] Compiling 1 Scala source to .../target/scala-2.11/test-classes...
[error] .../src/test/scala/TestFraction.scala:14: value should is not a member of Int
[error] f.numer should be > 0
[error] ^
什么是测试,导入和所有的完整源文件?
答案 0 :(得分:1)
如果你在这里检查scala测试的github存储库,你可以在这里找到一些额外的代码
对于您的来源,这是导入和结构
import org.scalatest.{Matchers, FlatSpec}
import org.scalatest.prop.PropertyChecks
class Fraction(n: Int, d: Int) {
require(d != 0)
require(d != Integer.MIN_VALUE)
require(n != Integer.MIN_VALUE)
val numer = if (d < 0) -1 * n else n
val denom = d.abs
override def toString = numer + " / " + denom
}
class PropertySpec extends FlatSpec with PropertyChecks with Matchers {
forAll { (n: Int, d: Int) =>
whenever(d != 0 && d != Integer.MIN_VALUE
&& n != Integer.MIN_VALUE) {
val f = new Fraction(n, d)
if (n < 0 && d < 0 || n > 0 && d > 0)
f.numer should be > 0
else if (n != 0)
f.numer should be < 0
else
f.numer should be === 0
f.denom should be > 0
}
}
val invalidCombos =
Table(
("n", "d"),
(Integer.MIN_VALUE, Integer.MIN_VALUE),
(1, Integer.MIN_VALUE),
(Integer.MIN_VALUE, 1),
(Integer.MIN_VALUE, 0),
(1, 0)
)
forAll(invalidCombos) { (n: Int, d: Int) =>
evaluating {
new Fraction(n, d)
} should produce[IllegalArgumentException]
}
}
答案 1 :(得分:1)
最新版本的scalatest未实现evaluating
,并将===
标记为过时。
因此,我将示例重写为:
import org.scalatest._
import org.scalatest.prop.PropertyChecks
protected class Fraction(n: Int, d: Int) {
require(d != 0 && d != Integer.MIN_VALUE && n != Integer.MIN_VALUE)
val numer = if (d < 0) -1 * n else n
val denom = d.abs
override def toString = numer + " / " + denom
}
class SscceProps extends FlatSpec with PropertyChecks with Matchers {
it should "valid combos" in { forAll { (n: Int, d: Int) =>
whenever(d != 0 && d != Integer.MIN_VALUE && n != Integer.MIN_VALUE) {
val f = new Fraction(n, d)
if (n < 0 && d < 0 || n > 0 && d > 0) f.numer should be > 0
else if (n != 0) f.numer should be < 0
else f.numer shouldBe 0
f.denom should be > 0
}
}}
it should "invalid combos" in {
forAll(Table(
("n", "d"),
(Integer.MIN_VALUE, Integer.MIN_VALUE),
(1, Integer.MIN_VALUE),
(Integer.MIN_VALUE, 1),
(Integer.MIN_VALUE, 0),
(1, 0)
)) { (n: Int, d: Int) =>
an[IllegalArgumentException] should be thrownBy {new Fraction(n, d)}}
}
}