spock測試框架,引用官方文檔的描述:
Spock is a testing and specification framework for Java and Groovy applications. What makes it stand out from the crowd is its beautiful and highly expressive specification language. Thanks to its JUnit runner, Spock is compatible with most IDEs, build tools, and continuous integration servers. Spock is inspired from JUnit, jMock, RSpec, Groovy, Scala, Vulcans, and other fascinating life forms.
這篇文章主要是簡單介紹了spock的Data Driven Testing
數據啟動測試:
通常,多次運行相同的測試代碼,具有不同的輸入和預期結果是有用的
example:
class MathSpec extends Specification {
def "maximum of two numbers"() {
expect:
// exercise math method for a few different inputs
Math.max(1, 3) == 3
Math.max(7, 4) == 7
Math.max(0, 0) == 0
}
}
這個例子的寫法簡單,但是存在一些缺點:
代碼和數據混合,不能輕易地獨立更改
- 數據不能自動生成或從外部來源獲取
- 為了多次運行相同的代碼,必須將其復制或提取為單獨的方法
- 如果發生故障,可能不會立即清楚哪些輸入導致故障
- 多次執行相同的代碼不會像執行單獨的方法那樣受益于相同的隔離
Spock的數據驅動測試
數據測試驅動解決了這個問題,首先引入了三個數據變量
class MathSpec extends Specification {
def "maximum of two numbers"(int a, int b, int c) {
expect:
Math.max(a, b) == c
...
}
}
在完成邏輯的測試部分,我們還需要提供相應的數據,這些工作則是在 where:
保存相應的數據塊。
databales
固定數據集,
class MathSpec extends Specification {
def "maximum of two numbers"(int a, int b, int c) {
expect:
Math.max(a, b) == c
where:
a | b | c
1 | 3 | 3
7 | 4 | 7
0 | 0 | 0
}
}
表的第一行聲明了數據變量,表的后續行,保存了相應的值。對于其中的每一行,feature method
將都執行一次,稱之為方法的迭代。
Tips
數據表必須至少有兩列。單列表可以寫成:
where:
a | _
1 | _
7 | _
0 | _
Method Unrolling
@Unroll
spock里的一個注解:
A method annotated with @Unroll will have its iterations reported independently:
有@Unroll的方法對每一個迭代都有自己的獨立報告。
example:
@Unroll
def "maximum of two numbers"() {
...
}
maximum of two numbers[0] PASSED
maximum of two numbers[1] FAILED
Math.max(a, b) == c
| | | | |
| 7 4 | 7
42 false
maximum of two numbers[2] PASSED
This tells us that the second iteration (with index 1) failed.
資料來源:spock doc:
http://spockframework.org/spock/docs/1.1/data_driven_testing.html
作者水平有限,出現錯誤請您指正,謝謝。