This episode is for subscribers only. Sign Up or Log in to watch it.

32. Introduction to Clojure Testing

Published 21 June 17

Testing libraries and frameworks are indispensable, but there’s no magic to how they work. Through implementing your own mini testing framework, you’ll learn how clojure.test does things under the hood.

While the main plot demonstrates how to write a function test-first, you’ll also meet several supporting characters, like preconditions, dynamic bindings, and even a macro. Finally the mask comes off. It was clojure.test all this time!

Show notes

A great exercise to do in any language is creating your own unit testing framework. While these frameworks can get pretty advanced, you actually need very little to be able to define and run tests.

In fact all you need to get started is one simple function, “assert equal”, which verifies that two values are the same.

If they are then nothing happens, if they’re not, then it throws an AssertionError, which is a built-in Error type, and we’ll give it a nice message: “I expected to get this thing, but instead I got that thing”.

(defn assert= [x y]
  (when (not= x y)
    (throw (AssertionError. (str "Expected " (pr-str y)
                                 " but got " (pr-str x))))))

(assert= 5 5)
;;=> nil

(assert= 5 6)
;;=> Unhandled java.lang.AssertionError
;;=> Expected (= 5 6) but got (not= 5 6)

And that’s all you need, now you can start writing tests. A test in this case means a piece of code that verifies the behavior of some other piece of code.

Let’s try it out by writing a function that converts Hiccup syntax to the format used by clojure.xml. Besides the actual implementation, I’ll also write a second function, which will act as the test.

(defn hiccup->cljxml [h]

(defn test-hiccup->cljxml []