For unit testing my clojure code, I decided to try a little trick which
I wasn't sure would work. I have a model namespace that defines the
application state, which could be a rather large object that's
computationally expensive to create and maintain. Rather than use
with-redefs everywhere, I attempted to mock out the entire
The idea was pretty straightforward:
- The source file name dictates the primary namespace, so the first form declares the namespace of our test cases.
- Next, we define a namespace that will serve as the model fake. We define a macro that defines a standardized test context, and then a set of functions that will be used to mock out the real namespace functions.
- Now, back in the main namespace, we create a fixture that switches to the namespace being tested, renames the model alias to point to the fake, runs the tests, and then switches the alias back to the correct namespace.
Sounds great in theory, but (fortunately) this doesn't work. I have
verified that the namespace is indeed switched. However, clojure seems
to compile in the namespace resolved symbol at the time of compilation.
with-redefs works, switching namespace reference