單元測試spock框架基礎

2022-07-29 07:33:07 字數 1534 閱讀 8432

spock基礎

1:fields 字段(屬性)

2:fixture methods 骨架方法

def setup(){} 每個功能(測試)方法之前執行的方法

def cleanup(){} 每個功能(測試)方法之後執行的方法

def setupspec(){} 第乙個功能(測試)方法之前執行的方法

def cleanupspec(){} 最後乙個功能(測試)方法之後執行的方法

3:feature methods 功能(測試)方法

def "sum should return param1+param2"()

4:blocks 每個feature method又被劃分為不同的block,不同的block處於測試執行的不同階段,在測試執行時,各個block按照不順序和規則被執行

4.1 setup/given block 在這個block中會放置與這個測試函式相關的初始化程式 *** 放在功能(測試)方法最前面 ***

4.2 when: then: block when和then是搭配使用,在when執行待測試的函式,在when中判斷是否符合預期

4.3 assert 斷言

在expect: then:會預設assert所有返回值是boolean型的頂級語句

異常斷言 thrown(exception)

沒有丟擲異常 notthrown(exception)

5:where blocks

傳統的測試邊界、測試異常分支,依賴反覆呼叫:

math.max(1,3) == 3 math.max(7,3) == 7 math.max(0,0) == 0 //這裡呼叫了三次

spock框架,提供了優雅:

expect:

math(a,b) == c

where:

a | b | || c

1 | 3 | || 3

7 | 3 | || 7

0 | 0 | || 0

6:互動測試(模組與模組之間) 類s,依賴類d提供的m方法

class s

public void t()

}class d

}測mock可以分為以下幾個步驟:

1) 通過mock(d)來得到乙個類d的例項; d = mock(d)

2) 在setup()方法中將d設定為類s的使用例項; s s = new s(d)

3) 在given block中,給出m方法的模擬返回資料; sdata = true

4) 在when block中,呼叫d的方法,使用 >> 將輸出指向 sdata; d.m(_ as string) >> sdata

5) 在then方法中,給出判定表示式,其中判定表示式可以引用where子句的變數; s.t() == "ok"

class stest extends specification

def "t"()

}參考文件:

(mock)

spock框架進行單元測試的學習與實踐

乙個穩定的系統少不了單元測試,單元測試 又稱為模組測試,unit testing 是針對程式模組 軟體設計的最小單位 來進行正確性檢驗的測試工作。對於物件導向程式設計,最小單元就是方法,包括父類 抽象類 或者子類中的方法。所以單元測試的特點 而單元測試的應用場景一般主要有這幾個 spock是基於ju...

go Test 單元測試 測試框架

1.建立乙個名為 test.go 的檔案 如果是包中的單元測試,就在包所在目錄下建立該檔案 並將下面的 新增到其中,函式命名統一為test t testing.t package main 包中的單元測試main替換成包名 import testing func testsum t testing....

Qt單元測試框架

qtestlib 框架提供了乙個簡單易用的單元測試框架,需要在工程檔案中新增qt testlib。先看乙個簡單的例子 此外,qt還提供了以下四個會被自動呼叫的private slot inittestcase 在測試開始前被呼叫 cleanuptestcase 在測試結束後被呼叫 init 每個測試...