DAY 29
0
Software Development

# 測試

## 事前準備

``````(ns clj-test.core-test
(:require [clojure.test :refer :all]))
``````

``````(require '[clojure.test :refer :all])
``````

## 斷言

### is

``````(is (= 4 (+ 2 2)))
;; => true
(is (.startsWith "abcde" "ab"))
;; => true
(is (instance? Integer 256))
;; => FAIL in () (form-init542440103815122923.clj:1)
;; => expected: (instance? Integer 256)
;; =>   actual: java.lang.Long
;; => false
``````

### are

``````(are [x y] (= x y)
4 (+ 2 2)
2 (+ 1 1))
;; => true
``````

``````(is (= 4 (+ 2 2)))
(is (= 2 (+ 1 1)))
``````

### thrown?

``````(is (thrown? ArithmeticException (/ 1 0)))
``````

## 測試案例

### 撰寫

``````(deftest addition
(is (= 4 (+ 2 2)))
(is (= 7 (+ 3 4))))
``````

``````(deftest arithmetic
(subtraction))
``````

### 說明文字

``````(is (= 5 (+ 2 2)) "Crazy arithmetic")
;; => FAIL in () (form-init542440103815122923.clj:1)
;; => Crazy arithmetic
;; => expected: (= 5 (+ 2 2))
;; =>   actual: (not (= 5 4))
;; => false
``````

``````(deftest arithemetic-test
(testing "Arithmetic"
(testing "with positive integers"
(is (= 4 (+ 2 2)))
(is (= 7 (+ 3 4))))
(testing "with negative integers"
(is (= -4 (+ -2 -2)))
(is (= -1 (+ 3 -4))))))
``````

### 執行

``````(run-tests 'your.namespace 'some.other.namespace)
``````

``````(run-tests)
;; =>
;; => Testing user
;; =>
;; => Ran 2 tests containing 6 assertions.
;; => 0 failures, 0 errors.
;; => {:test 2, :pass 6, :fail 0, :error 0, :type :summary}
``````

``````\$ lein test

lein test clj-test.core-test

lein test :only clj-test.core-test/a-test

FAIL in (a-test) (core_test.clj:7)
FIXME, I fail.
expected: (= 0 1)
actual: (not (= 0 1))

Ran 1 tests containing 1 assertions.
1 failures, 0 errors.
Tests failed.
``````

### 治具

`clojure.test` 中，Fixture 只是一個簡單的函式，它只接受一個參數。這個參數就是待執行的測試案例，如果想要在執行測試案例前後做一些準備或善後作業，只要在測試案例前後執行即可，範例如下：

``````(defn my-fixture [test-fn]
;; 在這裡設定或啓動必須事先準備好的事物
(test-fn) ;; 呼叫測試案例
;; 在這裡做善後工作
)
``````

Fixture 分爲兩種，一種是只需要執行一次，另一種是針對每個測試案例都會執行一次。以下是使用範例：

``````(use-fixtures :once load-data-fixture)   ;; 只執行一次
``````

## 回顧

（本篇文章同步刊登於 GitHub，歡迎在文章下方留言或發送 PR 給予建議與指教）