GeekFactory

int128.hatenablog.com

SpockでClosureのコールバックをテストする

Spockでテストを書いている時に Closure のコールバックをどうやってテストするか調べたのでメモ。

例えば Hoge#process(Closure) というメソッドがあるとします。何かを処理したら結果が Closure に渡される仕様とします。

class Hoge {
  /**
   * ほげを処理したらハンドラが呼ばれるよ。
   */
  void process(Closure callbackHandler) {
    def results = [] as List<Hoge>    // 何かの処理結果
    results.each(callbackHandler)
  }
}

これをテストするには Closure のモックを作ってメソッド呼び出しをアサートすればおkです。意外と普通でした。

class HogeSpec extends Specification {
  def "process a hoge"() {
    given:
    def input1 = new Input()
    def result1 = new Result()
    def hoge = new Hoge(input1)

    def handler = Mock(Closure)

    when:
    hoge.process(handler)

    then:
    // result1がハンドラに渡されるべし
    1 * handler.call(result1)
  }
}