0

我无法让 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都是错误的。我一直在摆弄它并试图提出解决方案;理想情况下,我有两个任意生成器,一个生成“好”Credit实例,一个尝试生成坏实例。

也许有更好的方法?

任何帮助表示赞赏。谢谢!

4

0 回答 0