Clojureで単体テストメモ〜clojure.test と Midje〜

Clojureでの単体テストについてメモ。
ざっと、以下の選択肢があるよう。

  • clojure.test 標準テストライブラリ
  • Midje テストフレームワーク。可読性の高いテスト記述をサポートする
  • test.generative テストデータ生成、テスト実行ライブラリ。期待値ではなく関数の性質を記述し、乱数引数に対する結果がその性質を満たすかをテストする

今回は、 clojure.test と Midje についてメモ。

clojure.test

利用例
  • テスト対象(src/testapp/core.clj)
(ns testapp.core)

(defn square "自乗" [x] (* x x))
  • テストコード(test/testapp/core_test.clj)
(ns testapp.core-test
  (:use clojure.test
        testapp.core))

; is 利用の場合
(deftest square-test-example01
  (testing "自乗"
    (is (= 4 (square 2)))))

; are 利用の場合
(deftest square-test-example02
  (testing "自乗"
    (are [y x] (= y (square x))
          1 1
          4 2
          9 3)))

; testing の階層化も可能
(deftest square-test-example03
  (testing "squareは"
    (testing "引数の自乗を返す"
      (are [y x] (= y (square x))
            1 1
            4 2
            9 3))
    (testing "正の数を返す"
      (are [x] (<= 0 (square x))
            -1
            0
            1))
    (testing "数字以外が渡された場合はClassCastExceptionを投げる"
      (are [x] (thrown? java.lang.ClassCastException (square x))
            "hoge"
            [1]))))
Leiningenでテスト実行
lein test
REPLでテスト実行
(ns testapp.core-test)
(run-tests)

Midje

「テストコード => 期待値」という直感的な記述ができるのが嬉しい。

導入
  • project.clj の :profiles に以下を追加
{:dev {:dependencies [[midje "1.5.1"]]}}
  • project.clj の :plugins に以下を追加
[lein-midje "3.0.0"]
利用例
  • テストコード(test/testapp/core_test.clj)
(ns testapp.core-test
  (:use midje.sweet
        testapp.core))

(facts "square関数"
  (fact "自乗である"
    (square 1) => 1
    (square 2) => 4))
テスト実行
lein midje