書寫測(cè)試用例一個(gè)步驟是書寫測(cè)試的預(yù)期結(jié)果。
Spec2 中缺省 Specification Trait 是函數(shù)化的,也就是說(shuō) Example 的 Result 值為代碼中的最后一條語(yǔ)句提供。比如下面的示例,永遠(yuǎn)不會(huì)失敗,這是本例的第一個(gè)測(cè)試的結(jié)果給丟掉了。
"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")
上面的函數(shù)化需要仔細(xì)指明所有的期望,有時(shí)你可能覺得這樣很麻煩,比如還是用什么的那個(gè)不會(huì)失敗的例子:
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")
}
}
這個(gè)例子來(lái)執(zhí)行不會(huì)報(bào)失敗,我們希望在執(zhí)行“hello” must have size(10000)報(bào)錯(cuò),不繼續(xù)執(zhí)行下面的測(cè)試,此時(shí)我們可以使用 org.specs2.matcher.ThrownExpectations,此時(shí)如果將這個(gè) Trait 混合到定義的規(guī)范中,所有沒有達(dá)到期望值的測(cè)試都會(huì)拋出 FailureException 異常,Example 之后的測(cè)試也不執(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")
}
}
這個(gè)測(cè)試的第一個(gè)檢測(cè)“hello” must have size(10000)失敗,整個(gè) Example 失敗,后續(xù)的測(cè)試也不會(huì)執(zhí)行。