Spock は素晴らしい!のですが、最大限機能を生かしきれてないと、よく感じるのでメモ。
基本形
package net.bucyou
import spock.lang.Specification
class SampleSpecification extends Specification {
// すべての feature (テスト) 前に実行される
def setup() {
}
// すべての feature (テスト) 後に実行される
def cleanup() {
}
// 最初の feature (テスト) 前に実行される
def setupSpec() {
}
// 最後の feature (テスト) 後に実行される
def cleanupSpec() {
}
// feature method (テスト)
def "うどんをたべるとうまい"() {
given:
def i = ..
def udon = ..
when:
def result = i.eat(udon);
then:
result == "Umai"
}
}
うどんはうまい。
このとき、result == “Mazui” とかを仮に結果に入れてみると、やたら詳しく比較が出てくれます。
これは、IntelliJ IDEA の機能ではなく、Spock の機能のようです。
Map や List でも、同様に細かい比較を見ることができるので、大助かりであります。
featureの文法
feature は、setup, when, then, expect, cleanup, そして where の
6つのブロックによって構成されています。
いつも、Gherkin の影響で given を使っていたのですが、
これは、setup の エイリアスとして定義されているので、動作に問題はありません。
公式のドキュメントによると、流れは上のような感じ。
setup: データの準備とか (1)
when: 実際に何かを実行 (2)
then: 結果の検証 (3)
expect: 何かを実行して検証 (2,3)
cleanup: データのお掃除とか (4)
where: なんか図では、えらいことになってますが後述
then, when など順番を逆に書いたりすると、エラーって落ちたりするっぽいです。
when -> expect -> then というものダメです。
when, then, when, then と複数回書くのは問題ないようです。
then が前のブロックに続けて複数あるときなどは and も使えるようです。
where block
where は複数の入力データを、同じテスト (setup, when, then, cleanup) に通すときに便利なブロックです。
class SampleSpecification extends Specification {
def "where!!"() {
setup:
println "setup"
when:
println "when"
then:
println "then"
println "a=" + a
println "b=" + b
cleanup:
println "cleanup"
where:
a | b
1 | "Udon"
2 | "Soba"
}
}
これを実行すると、以下の様な結果がやってきます。
setup
when
then
a=1
b=Udon
cleanup
setup
when
then
a=2
b=Soba
cleanup
class SampleSpecification extends Specification {
def "where!!"() {
setup:
println "setup"
when:
println "when"
then:
println "then"
println "a=" + a
println "b=" + b
cleanup:
println "cleanup"
where:
a | b
1 | "Udon"
2 | "Soba"
}
}
こういう、表形式な書き方もできるので、テストをわかりやすくするためには
なかなかゴキゲンになれる機能ですね!
Mock については、また今度書きます。


