Friday, December 16, 2011

Clojure Mocks

A few weeks ago a I wrote an HTTP server using Java. While testing, I made heavy usage of Mock objects. I didn't use a mocking framework, just hand rolled mocks. The motivation for this can be seen here. Now that I'm finished with the server I have been working on a Clojure project. Having just written a Java server, I find myself wanting to use mocks to testing everything in Clojure. However, this can be difficult with Objects. Here is how I'm mocking using Clojure.

Dependency Injection


Dependency Injection can be used similarly to the way one would in Java. The only difference is that dependencies are now functions as opposed to objects.

Bindings


This is the method I have taken the most advantage of. You simply bind all functions that the function under test uses. Like so...

(def mock-called-count (atom 0)) (def mock-called-content (atom nil)) (defn mock [& args] (swap! mock-called-count #(inc %)) (reset! mock-called-content args)) (binding [interactor/create mock] (create @customer))
Here, the create function use the method create in the interactor namespace. So, with the binding in place, when the create function calls interactor/create, it will actually call the mock function. In this case, the mock function just stores the data given to it and increments a call count. However, the possibilities are endless.

So, with these two great methods of mocking in Clojure, who needs a mocking framework?

No comments:

Post a Comment