Where do you put your Clojure tests?

Summary: Where to put your tests is a common question. You could put them anywhere, but you want to pick a place that makes it easy to find, easy to exclude from production, and work well with your tools. My recommendation is to follow what most projects do, which takes care of all of these requirements.

You want to write some tests in Clojure. Maybe they're unit tests. Maybe they're integration tests. The first question you must answer is where do you put your tests?

And you don't want them just anywhere. You actually have some important requirements dealing with where they are:

  • They should not be compiled/run on production.
  • They need to be easily findable.
  • They should be runnable from the command line.
  • They should be runnable from the REPL.

Here's my recommendation, which is the de facto standard of organizing your tests. It works with Leiningen, CIDER, and vim-fireplace.

First, you make a new namespace structure in a test/ directory. It should mirror the src/ directory.

If you have:

src/
  lispcast/
    core.clj
    init.clj
    util.clj

Then your test directory should look like:

test/
  lispcast/
    core_test.clj
    init_test.clj
    util_test.clj

But also notice the second point: that the structure is the same, but the names are slightly different, but it a systematic way. It's really easy: you just add -test to the namespace name, which becomes _test in the file name.^1 Then, you put all the tests that test lispcast.core into lispcast.core-test. Now they're easy to find!

If you need to write a test that crosses two different namespaces (like an integration test might), then you can just make a new test namespace that doesn't correspond to one or the other.

Leiningen will load the test/ directory selectively, depending on if you're deploying to production (it won't load test/) or running the tests (it will load test/).

So, it's that easy. You are free, of course, to put the tests wherever you like. But this is my recommendation!

If you're getting into testing in Clojure, you should check out LispCast Intro to clojure.test. It's an interactive course. It has animations, screencasts, exercises, code samples, and text.


  1. Clojure file names have to replace - (hyphens) with _ (underscores) to be compatible with Java.