在下面的代码中,如何让Specs2执行第一次测试?当它失败时,“打印的”测试通过。由于forAll()
。
new Scope
部分中的代码未执行
println
语句仅用于跟踪输出。如果您看到任何以“one”开头的行,请告诉我。
空Scope
仅用于演示问题。这是从我在Scope
中实际使用变量的代码中删除的。
import org.scalacheck.Gen
import org.scalacheck.Prop._
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification
import org.specs2.specification.Scope
class TestingSpec extends Specification with ScalaCheck {
"sample test" should {
"print ones" in new Scope {
println("The first test passes, but should fail")
forAll(Gen.posNum[Int]) { (x: Int) =>
println("one: " + x)
(0 < x) mustNotEqual true
}
}
"print twos" in {
println("The second test passes and prints twos")
forAll(Gen.posNum[Int]) { (x: Int) =>
println("two: " + x)
(0 < x) mustEqual true
}
}
}
}
这是我的输出:
sbt> testOnly TestingSpec
The second test passes and prints twos
The first test passes, but should fail
two: 1
two: 2
two: 1
...
two: 50
two: 34
two: 41
[info] TestingSpec
[info]
[info] sample test should
[info] + print ones
[info] + print twos
[info]
[info] Total for specification TestingSpec
[info] Finished in 96 ms
[info] 2 examples, 101 expectations, 0 failure, 0 error
[info]
[info] Passed: Total 2, Failed 0, Errors 0, Passed 2
[success] Total time: 3 s, completed Apr 28, 2015 3:14:15 PM
P.S。我将项目依赖性从版本2.4.15更新为specs2 3.5。还有这个问题......
答案 0 :(得分:4)
这是因为放在Scope
中的任何内容都必须在出现故障时抛出异常。除非你执行它,否则ScalaCheck Prop
将不会执行任何操作,因此您的示例将始终通过。
解决方法是将Prop
转换为specs2 Result
,例如使用以下隐式:
import org.specs2.execute._
implicit class RunProp(p: Prop) {
def run: Result =
AsResult(p)
}
然后
"print ones" in new Scope {
println("The first test passes, but should fail")
forAll(Gen.posNum[Int]) { (x: Int) =>
println("one: " + x)
(0 < x) mustNotEqual true
}.run
}
答案 1 :(得分:0)
我发现的另一种方法是从 Prop
开始,然后将您的 Scope
定义如下:
"print ones" in forAll(Gen.posNum[Int]) { (x: Int) =>
new Scope {
println("The first test passes, but should fail")
println("one: " + x)
(0 < x) mustNotEqual true
}
}
与@Eric 的回答相比,我更喜欢这种方法,因为首先您不需要隐式类,其次您不必调用您可能会忘记的 run
。