鍍金池/ 教程/ Scala/ 期望結(jié)果
Spec2 可選的 Matcher(匹配運(yùn)算)
測試結(jié)果 Results
Specs2 的設(shè)計思想
Fragments API 簡介
簡介
期望結(jié)果
Spec2 內(nèi)置的 Matcher(匹配運(yùn)算)

期望結(jié)果

書寫測試用例一個步驟是書寫測試的預(yù)期結(jié)果。

函數(shù)化

Spec2 中缺省 Specification Trait 是函數(shù)化的,也就是說 Example 的 Result 值為代碼中的最后一條語句提供。比如下面的示例,永遠(yuǎn)不會失敗,這是本例的第一個測試的結(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")

Thrown

上面的函數(shù)化需要仔細(xì)指明所有的期望,有時你可能覺得這樣很麻煩,比如還是用什么的那個不會失敗的例子:

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ī)范中,所有沒有達(dá)到期望值的測試都會拋出 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í)行。

上一篇:簡介下一篇:Fragments API 簡介