为什么有时无法在 Spec2 中捕获异常?



scala测试代码:

import play.api.test._
import scala._
import org.specs2.execute.Result
object ThrowTest extends PlaySpecification {
  "throwA" should {
    "catch the exception test1" in {
      world must throwA[Exception]
    }
    "catch the exception test2" in {
      hello {
        world =>
          world must throwA[Exception]
      }
    }
  }
  def hello(action: (String) => Result) = {
    action(world)
  }
  def world: String = {
    throw new Exception("world-exception")
  }
}

为什么test1按我的预期工作,但test2不是,这会将异常抛到外部并且永远不会捕获它:

[info] ! catch the exception test2
[error]     Exception: world-exception (ThrowTest.scala:26)
[error] database.ThrowTest$.world(ThrowTest.scala:26)
[error] database.ThrowTest$.hello(ThrowTest.scala:22)
[error] database.ThrowTest$$anonfun$1$$anonfun$apply$4.apply(ThrowTest.scala:14)
[error] database.ThrowTest$$anonfun$1$$anonfun$apply$4.apply(ThrowTest.scala:14)
[info] Total for specification ThrowTest

因为对于测试 2,您的异常会在调用 action 之前hello 中抛出。 action是一个String => Result,你用world调用它,当计算时,它会抛出异常,因此,所有这些代码:

world =>world must throwA[Exception]

永远不会执行。

相关内容

  • 没有找到相关文章

最新更新