Spock

轉(zhuǎn)載自:http://www.itdecent.cn/p/3ee99b8c6be1

介紹

Spock是一個為groovy和java語言應(yīng)用程序來測試和規(guī)范的框架。這個框架的突出點在于它美妙和高效表達規(guī)范的語言。得益于JUnit runner,Spock能夠在大多數(shù)IDE、編譯工具、持續(xù)集成服務(wù)下工作。Spock的靈感源于JUnit,jMock, RSpec, Groovy, Scala, Vulcans以及其他優(yōu)秀的框架形態(tài)。
PS:如果有使用dubbo的同學,這里推薦一個dubbo-postman工具:dubbo-postman

基本概念描述

Spock要求具備基本的groovy和單元測試知識。如果是java程序員,則不需要對groovy感到陌生,因為會java基本就會使用groovy了。

Spock測試類的一般結(jié)構(gòu)

首先看一下測試模板方法的定義和JUnit的對比:

image

Spock基于Groovy,所以像寫java測試類一樣,需要先創(chuàng)建一個groovy文件。
在一個groovy文件里面的第一行:import spock.lang.*,同時這個類需要繼承Specification。
舉例:

class MyFirstSpecification extends Specification {
  // 變量字段
  // 測試模板方法
  // 測試方法
  // 測試幫助方法
}

Spock的模板方法說明:

def setupSpec() {}    // runs once -  before the first feature method
def setup() {}        // runs before every feature method
def cleanup() {}      // runs after every feature method
def cleanupSpec() {}  // runs once -  after the last feature method

定義變量:

def obj = new ClassUnderSpecification()
def coll = new Collaborator()

定義測試方法:

def "pushing an element on the stack"() {
  // 測試代碼塊,最重要的地方
}

代碼塊結(jié)構(gòu)和測試各個概念階段的映射:

image

代碼塊結(jié)構(gòu)在def定義的方法內(nèi)容里面:

given:
def stack = new Stack()
def elem = "push me"

when:   // 執(zhí)行需要測試的代碼
then:   // 驗證執(zhí)行結(jié)果

條件判斷:

when:
stack.push(elem)

then:
!stack.empty
stack.size() == 1
stack.peek() == elem

條件不滿足的情況輸出結(jié)果舉例:

Condition not satisfied:

stack.size() == 2
|     |      |
|     1      false
[push me]

驗證拋出異常舉例:

when:
stack.pop()

then:
thrown(EmptyStackException)
stack.empty

訪問異常內(nèi)容:

when:
stack.pop()

then:
def e = thrown(EmptyStackException)
e.cause == null

驗證不會拋出異常舉例:

//hashmap允許null的key
def "HashMap accepts null key"() {
  given:
  def map = new HashMap()

  when:
  map.put(null, "elem")

  then:
  notThrown(NullPointerException)
}

基于測試的交互,通過mock構(gòu)造依賴的外部對象

def "events are published to all subscribers"() {
  given:
  def subscriber1 = Mock(Subscriber)//通過Mock構(gòu)造一個依賴的對象
  def subscriber2 = Mock(Subscriber)
  def publisher = new Publisher()
  publisher.add(subscriber1)
  publisher.add(subscriber2)

  when:
  publisher.fire("event")

  then:
  1 * subscriber1.receive("event")//驗證方法名為receive,以及參數(shù)"event"為的方法執(zhí)行一次
  1 * subscriber2.receive("event")
}

expect代碼塊:

expect:
Math.max(1, 2) == 2

cleanup代碼塊

given:
def file = new File("/some/path")
file.createNewFile()

// ...

cleanup:
file.delete()

where代碼塊,可能是Spock最厲害的地方了:

def "computing the maximum of two numbers"() {
  expect:
  Math.max(a, b) == c

  where:
  a << [5, 3]//執(zhí)行兩次測試,值依次為5,3,下面類似
  b << [1, 9]
  c << [5, 9]
}

測試的時候幫助方法的處理:

def "offered PC matches preferred configuration"() {
  when:
  def pc = shop.buyPc()

  then:
  pc.vendor == "Sunny"
  pc.clockRate >= 2333
  pc.ram >= 4096
  pc.os == "Linux"
}

額外定義一個幫助方法:

def "offered PC matches preferred configuration"() {
  when:
  def pc = shop.buyPc()

  then:
  matchesPreferredConfiguration(pc)
}

def matchesPreferredConfiguration(pc) {
  pc.vendor == "Sunny"
  && pc.clockRate >= 2333
  && pc.ram >= 4096
  && pc.os == "Linux"
}

輸出結(jié)果,結(jié)果沒有顯示具體的哪個判斷失敗了:

Condition not satisfied:

matchesPreferredConfiguration(pc)
|                             |
false                         ...

使用assert可以達到這個目的:

void matchesPreferredConfiguration(pc) {
  assert pc.vendor == "Sunny"
  assert pc.clockRate >= 2333
  assert pc.ram >= 4096
  assert pc.os == "Linux"
}

最終輸出結(jié)果,可以看到具體的錯誤條件:

Condition not satisfied:

assert pc.clockRate >= 2333
       |  |         |
       |  1666      false
       ...

在預(yù)期值斷言的時候使用with:

def "offered PC matches preferred configuration"() {
  when:
  def pc = shop.buyPc()

  then:
  with(pc) {
    vendor == "Sunny"
    clockRate >= 2333
    ram >= 406
    os == "Linux"
  }
}

使用mock對象的時候也可以用with:

def service = Mock(Service) // has start(), stop(), and doWork() methods
def app = new Application(service) // controls the lifecycle of the service

when:
app.run()

then:
with(service) {
  1 * start()
  1 * doWork()
  1 * stop()
}

當多個預(yù)期值一起斷言的時候使用verifyAll :

def "offered PC matches preferred configuration"() {
  when:
  def pc = shop.buyPc()

  then:
  verifyAll(pc) {
    vendor == "Sunny"
    clockRate >= 2333
    ram >= 406
    os == "Linux"
  }
}

在沒有對象參數(shù)的時候也可以這樣:

expect:
  verifyAll {
    2 == 2
    4 == 4
  }

文檔規(guī)范:

given: "open a database connection"
// code goes here

and可以增加多個使代碼根據(jù)可讀性:

given: "open a database connection"
// code goes here

and: "seed the customer table"
// code goes here

and: "seed the product table"
// code goes here

測試行為規(guī)范的一般模式:
給定條件....
當怎么樣的時候...
應(yīng)該怎樣

given: "an empty bank account"
// ...
when: "the account is credited $10"
// ...

then: "the account's balance is $10"
// ...

擴展注解:
@Timeout 設(shè)置方法執(zhí)行的時間
@Ignore 跳過這個測試方法和JUnit類似
@IgnoreRest 跳過其他所有的測試方法,只執(zhí)行這個測試方法

數(shù)據(jù)驅(qū)動測試

在where里面可以通過數(shù)據(jù)表格,數(shù)據(jù)管道,指定變量三種情況對不同的測試case進行賦值,特別是在當需要測試很多種情況的的時候,這個模式具有非常高的可讀性和簡潔性:

...
where:
a | _
3 | _
7 | _
0 | _

b << [5, 0, 0]

c = a > b ? a : b

基于測試的交互

場景如下,一個發(fā)送者向多個訂閱者發(fā)送消息

class PublisherSpec extends Specification {
  Publisher publisher = new Publisher()
  Subscriber subscriber = Mock()
  Subscriber subscriber2 = Mock()

  def setup() {
    publisher.subscribers << subscriber // << is a Groovy shorthand for List.add()
    publisher.subscribers << subscriber2
  }

期待執(zhí)行一次接收方法:

def "should send messages to all subscribers"() {
  when:
  publisher.send("hello")

  then:
  1 * subscriber.receive("hello")
  1 * subscriber2.receive("hello")
}

斷言表達式解釋:

1 * subscriber.receive("hello")
|   |          |       |
|   |          |       關(guān)聯(lián)參數(shù)
|   |          關(guān)聯(lián)目標方法
|   關(guān)聯(lián)目標對象
執(zhí)行次數(shù)

在mock創(chuàng)建的時候可以定義多個交互行為:

class MySpec extends Specification {
    Subscriber subscriber = Mock {
        1 * receive("hello")
        1 * receive("goodbye")
    }
}

一個測試代碼的多個交互通過when區(qū)分:

when:
publisher.send("message1")

then:
1 * subscriber.receive("message1")

when:
publisher.send("message2")

then:
1 * subscriber.receive("message2")

結(jié)果輸出:

Too many invocations for:

2 * subscriber.receive(_) (3 invocations)

打樁:

很多時候我們測試的時候不需要執(zhí)行真正的方法,因為在測試代碼里面構(gòu)建一個真實的對象是比較麻煩的,特別是使用一些依賴注入框架的時候,因此有了打樁的功能:

interface Subscriber {
    String receive(String message)
}

模擬返回值:

subscriber.receive(_) >> "ok"

表達式解釋:

subscriber.receive(_) >> "ok"
|          |       |     |
|          |       |     任何參數(shù)的這個方法調(diào)用都會返回"ok"
|          |       argument constraint
|          method constraint
target constraint

需要調(diào)用多次返回不同結(jié)果的時候可以這樣定義:

subscriber.receive(_) >>> ["ok", "error", "error", "ok"]

有時候我們測試的一個方法調(diào)用了類的其他方法,而其他的方法可能依賴了外部的對象,為了避免引入外部對象,可以使用部分mock功能減少構(gòu)建外部對象的繁瑣:

// this is now the object under specification, not a collaborator
MessagePersister persister = Spy {
  // 這個方法的任意參數(shù)調(diào)用都返回true
  isPersistable(_) >> true
}

when:
persister.receive("msg")

then:
// when里面的receive會調(diào)用persist,前提是isPersistable是true,因為mock的值是true,這個方法一定會被調(diào)用
1 * persister.persist("msg")

和springboot集成

spring本身提供了spring-test測試模塊,需要和Spock一起使用的話,只需要在Specification類上面加上SpringApplicationConfiguration這個注解就可以了,如果是mvc應(yīng)用還需加上WebAppConfiguration這個,其他的使用和原來一樣。

maven配置

在pom.xml里面添加

<!-- Spock依賴 -->
    <dependency>
      <groupId>org.spockframework</groupId>
      <artifactId>spock-core</artifactId>
      <version>1.2-groovy-2.4</version>
      <scope>test</scope>
    </dependency>
    <!-- Spock需要的groovy依賴 -->
    <dependency> 
      <groupId>org.codehaus.groovy</groupId>
      <artifactId>groovy-all</artifactId>
      <version>2.4.15</version>
    </dependency>

<!--...... -->
<!--編譯插件配置: -->
 <plugin>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.20.1</version>
        <configuration>
          <useFile>false</useFile>
          <includes>
            <include>**/*Test.java</include><!--指定JUnit的測試類名稱后綴-->
            <include>**/*Spec.java</include><!--指定Spock的測試類名稱后綴-->
          </includes>
        </configuration>
      </plugin>

總結(jié)

Spock整體上是一個規(guī)范描述型的測試框架,測試代碼非常易讀。對于java程序員,上手非常容易,在學習的時候可以先在一個項目上使用,當你發(fā)下它的優(yōu)點的時候,你會盡可能的把其他的測試代碼也改成用Spock來寫,這個過程可能會花費你更多的時間,但是當你熟悉了以后,它帶給你的收益一定是值得的。不要猶豫,學習新框架最快的方式就是馬上動手。

參考鏈接

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容