Before
Spock是用于groovy项目的单元测试框架,这个框架简单易用,值得推广。
Coding
def "test when then expect"() { when: def x = Math.max(1, 2)
then:
x == 2
//可以简化成下面的
expect:
Math.max(1, 2) == 2
}
def "test setup or given"() {
// setup: // def stack = new Stack() // def elem = "push me"
//setup 与 given 等价
given:
def stack = new Stack()
def elem = "push me"
when:
stack.push(elem)
then:
!stack.empty
stack.size() == 1
stack.peek() == elem
when:
stack.pop()
then:
stack.empty
when:
stack.pop()
then:
//notThrown(EmptyStackException)
def e = thrown(EmptyStackException)
e.cause == null
}
def "test cleanup"() {
setup:
def stack = new Stack()
def elem = "push me"
when:
stack.push(elem)
then:
elem == stack.pop()
cleanup:
stack = null
elem = null
}
def "HashMap accepts null key"() {
setup:
def map = new HashMap()
when:
map.put(null, "elem")
then:
//thrown(NullPointerException)
notThrown(NullPointerException)
}
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
}
def "maximum of two numbers2"() {
expect:
Math.max(a, b) == c
where:
a | b || c
3 | 5 || 5
7 | 0 || 7
0 | 0 || 0
}
@Unroll
def "maximum of #a and #b should be #c"() {
expect:
Math.max(a, b) == c
//Unroll 当成三个方法执行,否则就是在for循环里面执行
where:
a | b || c
3 | 5 || 5
7 | 0 || 7
0 | 0 || 0
}
explain
如上方代码所见,spock每个feature method被划分为不同的block,不同的block处于测试执行的不同阶段,在测试运行时,各个block按照不同的顺序和规则被执行,如下:
package org.spockframework.runtime.model; public enum BlockKind { SETUP,//初始化资源,最前执行(与given等价) EXPECT,//期望,等同于assert(assert支持需要运行时配置VMOptions:java -ea) WHEN,//与then一起等同于expect THEN,//与when一起等同于expect CLEANUP,//清理资源,最后执行 WHERE;//循环跑测试 }
spock框架重点就是上面这些block,搞定!!!