Before
Spock是用于groovy项目的单元测试框架,这个框架简单易用,值得推广。
Coding
<dependencies> <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId> <version>2.4.4</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.4</version> <scope>test</scope> </dependency> <dependency> <groupId>org.spockframework</groupId> <artifactId>spock-core</artifactId> <version>1.0-groovy-2.4</version> <scope>test</scope> </dependency> <dependency> <groupId>org.spockframework</groupId> <artifactId>spock-spring</artifactId> <version>1.0-groovy-2.4</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.codehaus.gmaven</groupId> <artifactId>gmaven-plugin</artifactId> <version>1.5</version> </plugin> </plugins> </build>def "test when then expect"() { when: def x = Math.max(1, 2)
1 then: 2 x == 2 3 4 //可以简化成下面的 5 expect: 6 Math.max(1, 2) == 2 7} 8 9def "test setup or given"() {
// setup: // def stack = new Stack() // def elem = "push me"
1 //setup 与 given 等价 2 3 given: 4 def stack = new Stack() 5 def elem = "push me" 6 7 when: 8 stack.push(elem) 9 10 then: 11 !stack.empty 12 stack.size() == 1 13 stack.peek() == elem 14 15 when: 16 stack.pop() 17 18 then: 19 stack.empty 20 21 when: 22 stack.pop() 23 24 then: 25 //notThrown(EmptyStackException) 26 def e = thrown(EmptyStackException) 27 e.cause == null 28} 29 30def "test cleanup"() { 31 setup: 32 def stack = new Stack() 33 def elem = "push me" 34 35 when: 36 stack.push(elem) 37 38 then: 39 elem == stack.pop() 40 41 cleanup: 42 stack = null 43 elem = null 44} 45 46 47def "HashMap accepts null key"() { 48 setup: 49 def map = new HashMap() 50 51 when: 52 map.put(null, "elem") 53 54 then: 55 //thrown(NullPointerException) 56 notThrown(NullPointerException) 57} 58 59 60def "maximum of two numbers"() { 61 expect: 62 // exercise math method for a few different inputs 63 Math.max(1, 3) == 3 64 Math.max(7, 4) == 7 65 Math.max(0, 0) == 0 66} 67 68def "maximum of two numbers2"() { 69 expect: 70 Math.max(a, b) == c 71 72 where: 73 a | b || c 74 3 | 5 || 5 75 7 | 0 || 7 76 0 | 0 || 0 77} 78 79@Unroll 80def "maximum of #a and #b should be #c"() { 81 expect: 82 Math.max(a, b) == c 83 84 //Unroll 当成三个方法执行,否则就是在for循环里面执行 85 where: 86 a | b || c 87 3 | 5 || 5 88 7 | 0 || 7 89 0 | 0 || 0 90}
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,搞定!!!