spock是一款全能型的單元測試框架。
最近在作單元測試框架的調研和嘗試,目前肯定的方案框架包括是:spock,Junit,Mockito以及powermock。因爲自己使用Groovy的緣由,比較鍾情於spock到家,可是奈何兼容性比較差,特別是跟Mockito等框架的高級語法的兼容。不過這不妨礙spock是一個很是優秀的單元測試框架,特別體如今用例的形式和測試報告的展現方式以及報錯信息的展現(這個我最中意)。java
在簡單看過官方文檔以後作了一些簡單的Demo,分享給你們。(官方文檔貌似有段時間沒有更新了,若是用的話建議升級最新版)web
package com.FunTester.spock.pratice import org.slf4j.Logger import spock.lang.Shared import spock.lang.Specification import static com.fun.frame.SourceCode.getLogger class test01 extends Specification { @Shared int a = 10; @Shared Logger logger = getLogger(this.getClass().getName()) def setupSpec() { logger.info "測試類開始! ${logger.getName()}" } def setup() { logger.info "測試方法開始!" } def "這是一個測試"() { given: "準備測試數據" def s = 3 def ss = 3 expect: "驗證結果" s == ss } def "表達式測試,表達式左右運算符號"() { given: "準備數據" expect: "測試方法" z == x + y where: "校驗結果" x | y || z 1 | 0 || 1 2 | 1 || 3 } def "表達式測試,表達式左右對象方法"() { expect: name.size() == length where: name | length "Spock" | 5 "Kirk" | 4 "Scotty" | 6 "Sc3otty" | 7 } def "表達式測試,表達式左右對象方法,數組表示測試數據"() { expect: name.size() == length where: name << ["fjdslj", "fds"] length << [6, 3] } def "校驗對象"() { given: def per = new Per("fun", 12) expect: with(per) { name == "fun" age == 12 } } def "when then結構測試"() { when: def s = plus(3, 2) def ss = plus(3, 2) then: verifyAll { s == 3 ss == 3 } } /** * 測試方法 * @param i * @param j * @return */ def plus(int i, int j) { i } /** * 測試類 */ class Per { Per(String name, int age) { this.name = name this.age = age } String name int age } }
展現一下spock的測試報告:
編程