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

Fragments API 簡介

前面的例子

import org.specs2._

class HelloWorldAcceptanceSpec extends Specification { def is = s2"""

 This is a specification to check the 'Hello world' string

 The 'Hello world' string should
   contain 11 characters                                         $e1
   start with 'Hello'                                            $e2
   end with 'world'                                              $e3
                                                                 """

  def e1 = "Hello world" must have size(11)
  def e2 = "Hello world" must startWith("Hello")
  def e3 = "Hello world" must endWith("world")
}

實際上是使用 Fragment API,我們使用 Fragment API 重寫什么例子,它是一系列 Fragment 對象通過^運算符連接而成:

import org.specs2._

class HelloWorldAcceptanceSpec extends Specification { def is =

 "This is a specification to check the 'Hello world' string" ^
 "The 'Hello world' string should" ^
   "contain 11 characters"                                         ! e1 ^
   "start with 'Hello'"                                            ! e2 ^
   "end with 'world'"                                              ! e3

  def e1 = "Hello world" must have size(11)
  def e2 = "Hello world" must startWith("Hello")
  def e3 = "Hello world" must endWith("world")
}

其中的 Example 對象的格式為 “description” ! body. body 返回一個 Result 對象,當你直接使用 Fragment API 使用 ^ 運算符構(gòu)建 Text 和 Example 對象時有些規(guī)則需要注意,這些規(guī)則影響到結(jié)果的顯示格式。

規(guī)則

spec2 的結(jié)果顯示的布局缺省情況是自動完成,其顯示和源碼顯示類似。 其顯示規(guī)則如下:

  • 當一個 Example 跟在一個 Text 對象后面,它縮進顯示。
  • 兩個連續(xù)的 Example 對象,縮進層次相同。
  • 但一個 Text 對象跟在一個 Example 對象后面時,意味著你想顯示一個“輔助文字(子文字)”,因此這個 Text 對象縮進一級。

比如下面的例子:

"this is some presentation text"      ^
  "and the first example"             ! success^
  "and the second example"            ! success
}

顯示如下:

 this is some presentation text
 + and the first example
 + and the second example

如果你指定一個“子文字” ,則顯示如下:

this is some presentation text
+ and the first example
+ and the second example
  and in this specific context
  + one more example