Simplest Clojure Test


Here's how to set up clojure testing environment.

Let's start a new project directory and create a src directory:

mkdir src

Let's create the source file with src/calc.clj. There's a simple namespace declaration and function that adds 2 numbers.

(ns calc)

(def add [a b]
  (+ a b))

Now let's test that add function. We need a test runner. There are a couple. The most standard is test-runner. Prep for install by adding it to the dependencies list in you project root with vim deps.edn:

{:aliases
 {:test {:extra-paths ["test"]
         :extra-deps {io.github.cognitect-labs/test-runner
                      {:git/url "https://github.com/cognitect-labs/test-runner.git"
                       :sha "a85b3b02765fb68684ab9ee4a8598eacf7e471d2"}}
         :main-opts ["-m" "cognitect.test-runner"]
         :exec-fn cognitect.test-runner.api/test}}}

We are creating an alias that we can call to run tests, called :test.

Next, create a test directory to store the test file:

mkdir test

And create that test file with vim test/calc_test.clj:

(ns calc-test
  (:require [clojure.test :refer [is deftest]]
            [calc])

(deftest test-add
  (is (= 4 (calc/add 3 1))))

Note that the significant parts of this setup. For test-runner to find the test:

  1. Put the test files in the test/ directory.
  2. Use a -test-suffixed namespace.
  3. Define tests with deftest.

Now we can run the test via our alias by executing:

clj -X:test

This will give you some output like:

Running tests in #{"test"}

Testing calc-test

Ran 1 tests containing 1 assertions.
0 failures, 0 errors.

Does it get any simpler? What's your setup?