ScalaCheck之前/之后/周围?

时间:2012-09-17 14:07:21

标签: scala specs2 scalacheck

specs2具有BeforeAfterAround等特征,以便能够在setup / teardown代码中包装示例。

是否有任何东西可以支持为ScalaCheck属性的每个“迭代”设置和拆除测试基础架构,即ScalaCheck要测试的每个值或值集?

看起来像specs2的各种Before,After,Around特征是围绕返回或抛出specs2 Result实例而设计的,而Prop不是结果。

1 个答案:

答案 0 :(得分:2)

现在已在最新的1.12.2-SNAPSHOT中修复。你现在可以写:

import org.specs2.ScalaCheck
import org.specs2.mutable.{Around, Specification}
import org.specs2.execute.Result

class TestSpec extends Specification with ScalaCheck {
  "test" >> prop { i: Int =>
    around(i must be_>(1))
  }

  val around = new Around {
    def around[T <% Result](t: =>T) = {
      ("testing a new Int").pp
      try { t }
      finally { "done".pp }
    }
  }    
}

这将执行Property的“body”之前和之后的代码。

您还可以更进一步,创建一种支持方法,将隐式around传递给您的道具:

class TestSpec extends Specification with ScalaCheck {
  "test" >> propAround { i: Int =>
    i must be_>(1)
  }

  // use any implicit "Around" value in scope
  def propAround[T, R](f: T => R)
                      (implicit a: Around, 
                       arb: Arbitrary[T], shrink: Shrink[T], 
                       res: R => Result): Result =
    prop((t: T) => a(f(t)))

  implicit val around = new Around {
    def around[T <% Result](t: =>T) = {
      ("testing a new Int").pp
      try { t }
      finally { "done".pp }
    }
  }
}