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)
(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
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