Clojure test-is library examples and explanation – Basic
Clojure contrib comes with a testing framework test-is. Even though it is a small library it does its job. test-is consists many useful functions and macros to help us test our code. I am going to go through some of them and show some examples. Some examples I took it from http://richhickey.github.com/clojure-contrib/test-is-api.html
deftest
Is a macro to define a test function.
Usage
(deftest name & body)
Example
(deftest test-addition (is (= (+ 1 2) 3)))
is
It is a generic assertion macro. You will end up using this a lot in your test code.
Usage
(is form) (is form msg)
Examples
(is (= (+ 1 2) 3))
[or]
user> (is (= (+ 2 1) 3) "should be 3") true user> (is (= (+ 3 1) 3) "should be 3")
FAIL in clojure.lang.PersistentList$EmptyList@1 (NO_SOURCE_FILE:1) should be 3 expected: (= (+ 3 1) 3) actual: (not (= 4 3)) false
This “is” macro could be used to test exceptions too.
(is (thrown? c body)) (is (thrown-with-msg? c re body))
are
Sometimes just using “is” will become tedious.
(deftest test-addition (is (= (+ 2 1) 3)) (is (= (+ 0 0) 0)) (is (= (+ -1 -1) -2)))
Using “are” we could clean up this test function as
(deftest test-addition
(are [x y] (= x y)
3 (+ 2 1)
0 (+ 0 0)
-2 (+ -1 -1)))
The only problem using “are” is when a test fails it screws up line number where failure happened.
testing
This is my favorite macro. It allows me organize my tests.
Lets take this test
(deftest test-addition (is (= (+ 2 1) 3)) (is (= (+ 0 0) 0)) (is (= (+ -1 -1) -2)))
Imagine it is doing some complicated stuff. This test does not express intent. Using “testing” we can rewrite
(deftest test-addition
(testing "should add positive numbers"
(is (= (+ 2 1) 3)))
(testing "should add zeros"
(is (= (+ 0 0) 0)))
(testing "should be able to add negative numbers"
(is (= (+ -1 -1) -2))))
The best part if a test fails it prints the string next to “testing”
(test-addition) FAIL in (test-addition) (NO_SOURCE_FILE:1) should be able to add negative numbers expected: (= (+ -1 -1) -3) actual: (not (= -2 -3))
Happy testing …
