書寫測試用例一個步驟是書寫測試的預期結果。
Spec2 中缺省 Specification Trait 是函數化的,也就是說 Example 的 Result 值為代碼中的最后一條語句提供。比如下面的示例,永遠不會失敗,這是本例的第一個測試的結果給丟掉了。
"my example on strings" ! e1 // will never fail!
def e1 = {
"hello" must have size(10000) // because this expectation will not be returned,...
"hello" must startWith("hell")
}
因此正確的寫法為:
"my example on strings" ! e1 // will fail
def e1 = "hello" must have size(10000) and
startWith("hell")
上面的函數化需要仔細指明所有的期望,有時你可能覺得這樣很麻煩,比如還是用什么的那個不會失敗的例子:
import org.specs2._
class HelloWorldAcceptanceSpec extends Specification { def is = s2"""
This is a specification to check the 'Hello world' string
"my example on strings" $e1
"""
def e1 = {
"hello" must have size(10000) // because this expectation will not be returned,...
"hello" must startWith("hell")
}
}
這個例子來執(zhí)行不會報失敗,我們希望在執(zhí)行“hello” must have size(10000)報錯,不繼續(xù)執(zhí)行下面的測試,此時我們可以使用 org.specs2.matcher.ThrownExpectations,此時如果將這個 Trait 混合到定義的規(guī)范中,所有沒有達到期望值的測試都會拋出 FailureException 異常,Example 之后的測試也不執(zhí)行,比如修改后代碼:
import org.specs2._
import org.specs2.matcher.ThrownExpectations
class HelloWorldAcceptanceSpec extends Specification with ThrownExpectations { def is = s2"""
This is a specification to check the 'Hello world' string
"my example on strings" $e1
"""
def e1 = {
"hello" must have size(10000) // because this expectation will not be returned,...
"hello" must startWith("hell")
}
}
這個測試的第一個檢測“hello” must have size(10000)失敗,整個 Example 失敗,后續(xù)的測試也不會執(zhí)行。