2014-03-31 45 views
3

Scala的測試代碼:爲什麼有時在Spec2中無法捕獲異常?

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

由於測試2您的除之前的hello異常從action調用。 actionString => Result和你world其稱之爲 - 評估時 - 拋出一個異常,爲此,所有這些代碼:

world =>world must throwA[Exception] 

從不執行。

+0

只是爲了使它有點明確,你(@Freewind)在你的代碼中的hello函數中有什麼是:'val result = world;動作(結果)' –

相關問題