我无法获得specs2和scalacheck合作。我有一个简单的类Credit
,它接受1到59范围内的单个整数(超出此范围的任何内容都应该抛出异常)。
我想定义两个测试:1个验证肯定案例的测试(任何Credit(1)
... Credit(59)
成功验证);并且,该范围之外的任何Credit
都应该无法验证(它实际上应该在构造时抛出异常)。似乎正确的方法是定义一个Arbitrary[Credit]
生成器,如下所示:
implicit lazy val arbitraryCreditGenerator: Arbitrary[Credit] = Arbitrary(creditGenerator)
然后我也会定义一个arbitraryBadCreditGenerator
。
问题在于隐含使用任意,并试图找出使用prop
和我的两个不同任意实例的语法。
到目前为止我所拥有的是:
case class Credit(amount: Int)
object Credit {
implicit val creditValidator = validator[Credit] { c =>
c.amount should be > 0
c.amount should be < 60
}
}
class TestCreditModel extends Specification with ScalaCheck { def is = s2"""
Given a credit
When validation is performed
Then credits between 1 and 60 should be acceptable ${creditsAreValid}
And credits less than 1 or greater than 60 should not ${creditsAreInvalid}
"""
implicit lazy val arbitraryCreditGenerator: Arbitrary[Credit] = Arbitrary(creditGenerator)
val creditGenerator = Gen.choose(1,59).map(Credit(_))
val badCreditGenerator = (Gen.choose(-500, 500) suchThat (n => n < 1 || n > 59)).map(Credit(_))
def creditsAreValid = prop { (a: Credit) => validate(a).isSuccess must beTrue }
// Err... oops... how do I use my badCreditGenerator???
def creditsAreInvalid = prop { (a: badCreditGenerator) => validate(a).isSuccess must beFalse }
// ^ compile error... not defined
}
我使用Accord进行验证,因此任何创建具有无效范围的Credit
的尝试都将失败。
这不能编译,因为我的使用badCreditGenerator
都是错误的。我一直在摆弄它并试图找到解决方案;理想情况下,我有两个任意生成器,一个生成&#34;好&#34; Credit
个实例和一个试图生成错误的实例。
也许有更好的方法?
任何帮助表示赞赏。谢谢!