Skip to content
LumenaryAcademy
Professional 70 min

Testing, tooling and a complete project

clojure.test, the Clojure CLI and Leiningen in depth, the tools professionals use, ClojureScript, and a small program built the idiomatic way.

Code tested · 2AI-draftedAwaiting review by a computer scientist
MotivationH

From a file to a project

So far every program in this course has been a single file run from top to bottom. Real Clojure work happens in projects: many namespaces, a test suite, dependencies, a build that produces something deployable, and a set of tools that keep a team's code consistent. This last lesson covers that professional layer and then puts the whole course together in one complete program.

The good news is that Clojure's tooling follows the same philosophy as the language. Configuration is data (deps.edn is a map), tests are functions, and almost everything can be driven from the REPL. Once you see how the pieces fit, there is less to learn than the list of tool names suggests.

Worked examplesH

Testing with clojure.test

clojure.test ships with Clojure and is what most projects use, directly or through a runner. Its vocabulary is small:

FormMeaning
(deftest name body...)define a test, which is just a function with no arguments
(is expr) / (is expr "message")assert that expr is truthy, reporting both sides of = on failure
(testing "context" body...)label a group of assertions in failure reports
(are [args] template data...)repeat a template assertion over rows of data
(is (thrown? Class expr))assert that an exception of a class is thrown
(run-tests)run the tests of the current (or given) namespaces and print a summary
clojure
(ns grades.core-test
  (:require [clojure.test :refer [deftest is are testing run-tests]]
            [clojure.string :as str]))

(defn letter-grade [score]
  (cond
    (not (<= 0 score 100)) (throw (ex-info "Score out of range" {:score score}))
    (>= score 90) "A"
    (>= score 80) "B"
    (>= score 70) "C"
    :else "F"))

(defn initials [full-name]
  (->> (str/split full-name #"\s+")
       (map first)
       (apply str)
       (str/upper-case)))

(deftest letter-grade-test
  (testing "boundaries"
    (are [score grade] (= grade (letter-grade score))
      100 "A"
      90  "A"
      89  "B"
      80  "B"
      70  "C"
      69  "F"
      0   "F"))
  (testing "invalid scores are rejected"
    (is (thrown-with-msg? clojure.lang.ExceptionInfo #"out of range"
                          (letter-grade 101)))))

(deftest initials-test
  (is (= "AO" (initials "Ada Okafor")))
  (is (= "GGM" (initials "gabriel garcia marquez")))
  (is (= "LK" (initials "Lin  Kai"))))

(deftest deliberately-failing-test
  (is (= "A" (letter-grade 85)) "85 should be an A (it is not)"))

(let [summary (run-tests)]
  (println (select-keys summary [:test :pass :fail :error])))
text
Testing grades.core-test

FAIL in (deliberately-failing-test) (main.clj:39)
85 should be an A (it is not)
expected: (= "A" (letter-grade 85))
  actual: (not (= "A" "B"))

Ran 3 tests containing 12 assertions.
1 failures, 0 errors.
{:test 3, :pass 11, :fail 1, :error 0}

One test fails on purpose so you can see a failure report: the test name, the file and line, your message, the expression, and what it actually evaluated to. Because is is a macro, it sees the code of the assertion, not just its value, which is how it can print (not (= "A" "B")) instead of a bare "assertion failed". The are table expanded into seven assertions; together with the others that makes twelve.

Testing habits that suit Clojure:

  • Test the pure core. Functions that take and return data need no mocks, no setup and no teardown. This is where most tests in a Clojure codebase live, and they run in milliseconds.
  • Run tests from the REPL. Evaluate a deftest and call it like a function, or call (run-tests), without restarting anything. Editors bind both to keys.
  • Property-based tests with the test.check library generate hundreds of random inputs and check a property ("balances always sum to zero"); combined with spec, the generators can come from your data descriptions.
  • Fixtures (use-fixtures) wrap tests that need a database or a temporary directory, but keep them for the imperative shell.

In a project, tests live in a parallel test/ directory: the tests for src/fairshare/core.clj go in test/fairshare/core_test.clj, in the namespace fairshare.core-test.

ExplanationH

The toolchain professionals use

The Clojure CLI and deps.edn

A real deps.edn grows aliases, named bundles of extra paths, dependencies and options that you switch on from the command line:

clojure
{:paths ["src" "resources"]
 :deps  {org.clojure/clojure {:mvn/version "1.12.6"}}
 :aliases
 {:test  {:extra-paths ["test"]
          :extra-deps  {io.github.cognitect-labs/test-runner
                        {:git/tag "..." :git/sha "..."}}   ; copy the current tag and sha from its README
          :main-opts   ["-m" "cognitect.test-runner"]}
  :build {:deps       {io.github.clojure/tools.build {:git/tag "..." :git/sha "..."}}
          :ns-default build}}}

Libraries come from Maven Central and Clojars by version (:mvn/version), or straight from a Git repository by tag and commit (:git/tag, :git/sha), which the CLI supports natively. The CLI has three ways to run things:

CommandWhat it runs
clojure -M -m fairshare.corethe -main function of a namespace, with command-line arguments (-M means "main options")
clojure -M:testthe :test alias's main options: here, the test runner
clojure -X:some-aliasa function that takes one map of arguments (-X means "execute a function")
clojure -T:build ubera tool function, here build/uber from build.clj, without the project's own dependencies
clojure -X:deps treeprints the resolved dependency tree, useful when versions conflict

To deploy a service, teams typically write a short build.clj using tools.build that compiles the code ahead of time and packs it with all dependencies into an uberjar, then run it anywhere Java is installed with java -jar app.jar.

Leiningen

Many existing projects, and plenty of new ones, use Leiningen instead. Its project.clj holds the same information in a different shape:

clojure
(defproject fairshare "0.1.0-SNAPSHOT"
  :description "Split shared expenses fairly."
  :dependencies [[org.clojure/clojure "1.12.6"]]
  :main fairshare.core
  :profiles {:uberjar {:aot :all}})
TaskClojure CLILeiningen
start a REPLcljlein repl
run -mainclojure -M -m fairshare.corelein run
run testsclojure -M:test (with a runner alias)lein test
build an uberjarclojure -T:build uber (with build.clj)lein uberjar

Leiningen is "batteries included": templates, plugins and a fixed set of tasks. The CLI is smaller and composable: it only builds classpaths and runs functions, and everything else is a library you choose. Both are maintained and both are fine; the main practical advice is to learn whichever your codebase uses, and to recognise the other.

The rest of the kit

  • Editors and nREPL. Calva (VS Code), CIDER (Emacs), Cursive (IntelliJ) and Conjure (Neovim) connect to a running REPL, usually over nREPL, so you can evaluate forms, run tests and look up documentation from the editor.
  • clj-kondo is the standard linter: it finds unused bindings, wrong arities, misspelled keywords in destructuring and much more, as you type. Most teams run it in CI.
  • cljfmt (or zprint) formats code consistently, so code reviews are about meaning, not indentation.
  • Kaocha and Cognitect's test-runner run test suites from the command line and in CI.
  • Babashka is a fast-starting Clojure interpreter compiled to a native binary, used for shell scripts and build tasks where JVM start-up time would be annoying.
  • Clojars hosts community libraries; ClojureDocs collects community examples for every core function; Ask Clojure is the official question site.

ClojureScript, in brief

ClojureScript is Clojure compiled to JavaScript, released in 2011. It has the same syntax, the same persistent data structures, sequences, atoms and macros, but its host is the JavaScript runtime instead of the JVM: interop reaches JavaScript objects ((js/console.log "hi"), (.getElementById js/document "app")), there is a single thread (so refs and agents are absent, and core.async is popular), and numbers are JavaScript's. Most teams build it with shadow-cljs, which also makes npm packages easy to use, and write user interfaces with React wrappers such as Reagent and re-frame, whose "one atom holds the app state" design comes straight from lesson 6.

Code meant to run on both platforms goes in .cljc files, using reader conditionals where the hosts differ:

clojure
(defn now-ms []
  #?(:clj  (System/currentTimeMillis)
     :cljs (.now js/Date)))

This is how many libraries, and many companies' shared domain code, serve both a JVM back end and a browser front end from a single source. Other hosts exist too: ClojureCLR targets .NET, and newer projects such as ClojureDart (for Flutter) and jank (native code via LLVM) are under active development as of 2026.

Worked examplesH

Project: splitting shared expenses

Here is a complete program in the style this course has taught: data described with spec, a pure core of small functions, a thin shell that does the printing, and tests. It splits the costs of a shared trip and works out who should pay whom.

Money is stored as integer cents, never as floating-point numbers, so no rounding errors creep in; when an amount does not divide evenly, the leftover cents are handed out one at a time.

clojure
(ns fairshare.core
  "Split shared expenses fairly and work out who should pay whom."
  (:require [clojure.spec.alpha :as s]
            [clojure.string :as str]
            [clojure.test :refer [deftest is run-tests]]))

;; ---------------------------------------------------------------- data shape

(s/def ::person (s/and string? (complement str/blank?)))
(s/def ::paid-by ::person)
(s/def ::cents pos-int?)
(s/def ::among (s/coll-of ::person :kind vector? :min-count 1 :distinct true))
(s/def ::expense (s/keys :req-un [::paid-by ::cents ::among]))

(defn validate! [expenses]
  (doseq [e expenses]
    (when-not (s/valid? ::expense e)
      (throw (ex-info "Invalid expense" {:expense e
                                         :problems (s/explain-str ::expense e)}))))
  expenses)

;; ---------------------------------------------------------------- pure core

(defn shares
  "Splits cents equally among people; leftover cents go to the first people."
  [cents people]
  (let [n (count people)
        base (quot cents n)
        extra (rem cents n)]
    (zipmap people
            (map-indexed (fn [i _] (if (< i extra) (inc base) base)) people))))

(defn expense->deltas
  "What one expense does to each person's balance (positive = is owed)."
  [{:keys [paid-by cents among]}]
  (merge-with + {paid-by cents} (update-vals (shares cents among) -)))

(defn balances [expenses]
  (->> expenses
       (map expense->deltas)
       (apply merge-with + {})
       (remove (comp zero? val))
       (into (sorted-map))))

(defn settlements
  "Greedy plan: the biggest debtor pays the biggest creditor, until all are even."
  [balances]
  (loop [owed  (sort-by (juxt (comp - val) key) (filter (comp pos? val) balances))
         owing (sort-by (juxt val key) (filter (comp neg? val) balances))
         plan  []]
    (if (or (empty? owed) (empty? owing))
      plan
      (let [[creditor credit] (first owed)
            [debtor debt] (first owing)
            amount (min credit (- debt))
            owed'  (if (= amount credit) (rest owed) (cons [creditor (- credit amount)] (rest owed)))
            owing' (if (= amount (- debt)) (rest owing) (cons [debtor (+ debt amount)] (rest owing)))]
        (recur owed' owing' (conj plan {:from debtor :to creditor :cents amount}))))))

(defn money [cents]
  (format "%s%d.%02d" (if (neg? cents) "-" "") (quot (abs cents) 100) (rem (abs cents) 100)))

(defn report [expenses]
  (let [bals (balances (validate! expenses))]
    (concat
      ["Balances:"]
      (for [[who cents] bals] (format "  %-7s %8s" who (money cents)))
      ["Payments:"]
      (for [{:keys [from to cents]} (settlements bals)]
        (format "  %s pays %s %s" from to (money cents))))))

;; ---------------------------------------------------------------- shell

(def trip
  [{:paid-by "Amara" :cents 12000 :among ["Amara" "Bilal" "Chloe"] :note "groceries"}
   {:paid-by "Bilal" :cents 4500  :among ["Bilal" "Chloe"]          :note "taxi"}
   {:paid-by "Chloe" :cents 1000  :among ["Amara" "Bilal" "Chloe"] :note "ice cream"}
   {:paid-by "Amara" :cents 2000  :among ["Dev" "Amara"]            :note "museum"}])

(defn -main [& _args]
  (run! println (report trip)))

(-main)

;; ---------------------------------------------------------------- tests

(deftest shares-are-fair
  (is (= {"a" 334, "b" 333, "c" 333} (shares 1000 ["a" "b" "c"])))
  (is (= 1000 (reduce + (vals (shares 1000 ["a" "b" "c"]))))))

(deftest balances-sum-to-zero
  (is (zero? (reduce + (vals (balances trip))))))

(deftest settlements-settle-everyone
  (let [bals (balances trip)
        after (reduce (fn [b {:keys [from to cents]}]
                        (-> b (update from + cents) (update to - cents)))
                      bals
                      (settlements bals))]
    (is (every? zero? (vals after)))))

(deftest invalid-input-is-rejected
  (is (thrown? clojure.lang.ExceptionInfo
               (validate! [{:paid-by "Amara" :cents -5 :among ["Amara"]}]))))

(let [{:keys [fail error]} (run-tests)]
  (when (pos? (+ fail error))
    (System/exit 1)))
text
Balances:
  Amara      86.66
  Bilal     -20.83
  Chloe     -55.83
  Dev       -10.00
Payments:
  Chloe pays Amara 55.83
  Bilal pays Amara 20.83
  Dev pays Amara 10.00

Testing fairshare.core

Ran 4 tests containing 5 assertions.
0 failures, 0 errors.

How it is built

Check the arithmetic by hand once. The groceries cost 120.00 split three ways, 40.00 each, so Amara is owed 80.00 and Bilal and Chloe each owe 40.00. The taxi moves Bilal up by 22.50 and Chloe down by 22.50. The ice cream, 10.00 split three ways, does not divide evenly: Amara's share is 3.34 and the others pay 3.33, because the leftover cent goes to the first person listed. The museum leaves Amara 10.00 better off and Dev 10.00 down. The four balances add to exactly zero, which is what the second test checks.

Walk through the design from the inside out:

  • The data shape comes first. The specs say what an expense is: a payer, a positive number of cents, and a non-empty vector of distinct people. validate! checks input at the boundary and throws ex-info with spec's explanation attached. Extra keys such as :note are allowed, because spec maps are open.
  • Each function does one thing. shares splits an amount, expense->deltas turns one expense into a map of balance changes, balances sums all of them with merge-with +, and settlements plans the payments. Each takes and returns plain data, so each can be called in the REPL with a small example. update-vals (Clojure 1.11) negates every share in one call.
  • loop/recur where it earns its place. The settlement plan is genuinely stateful (two shrinking queues and a growing plan), so it uses an explicit loop. Everything else is pipelines. Every payment in the greedy plan settles at least one person completely, so nn people with non-zero balances never need more than n−1n - 1 payments; finding the plan with the fewest possible payments is a much harder problem, and this one is good enough for friends on a trip.
  • The shell is thin. report produces lines of text as data; only -main prints. In a real project the file would end after the shell, the tests would live in test/fairshare/core_test.clj, and you would run clojure -M -m fairshare.core and clojure -M:test instead of calling -main and run-tests at the bottom.
  • Failing tests fail the process. The last form exits with status 1 if anything failed, the same contract a CI system expects from a test runner.

Ideas for extending it

Read the expenses from an EDN file given on the command line (clojure.edn/read-string on slurp); support unequal splits with a :weights map; add a property-based test that generates random trips and checks that balances always sum to zero; or turn report into a small web page with ClojureScript and Reagent.

Further reading

Where to go next

You now know the language's core, its approach to data and state, its interop and macros, and the tools of a working Clojure developer. Some good next steps:

  • Read real code. The source of clojure.core itself is readable and instructive (source at the REPL shows any function). Small, well-known libraries are the next step.
  • Practise. The Clojure track on Exercism offers exercises with mentoring.
  • Books. Clojure for the Brave and True is free online; the official site keeps a list of books for every level.
  • Talks and essays. Rich Hickey's talks on simplicity and on values and state, and the essays in the "About" section of clojure.org, explain the thinking behind the design better than any summary.
  • Community. Ask Clojure and ClojureVerse are friendly places to ask questions, and the community is known for being welcoming to newcomers.
Optional Christian reflection · Simple is not the same as easy

A reflection from the Christian tradition that inspires Lumenary Academy. It is not part of the mathematics and you are welcome to skip it.

Clojure's community often distinguishes simple (not tangled together, one thing doing one job) from easy (familiar, close at hand). Parentheses, immutable values and pure functions are not easy at first, but they are simple, and simplicity is what lets a program stay understandable as it grows. Much of what is worth learning, in programming and elsewhere, works this way: the discipline that feels unfamiliar today is what makes freedom possible tomorrow.

Exercises

Exercises

1. Testing, tooling and a complete project

Warm-upComputational

How many assertions does this are form make?

(are [x y] (= x (inc y))
  2 1
  3 2
  4 3)

2. Testing, tooling and a complete project

Warm-upHuman

Which command runs the -main function of the namespace fairshare.core with the Clojure CLI?

Choose one

3. Testing, tooling and a complete project

CoreComputational

Using the project's money function,

(defn money [cents]
  (format "%s%d.%02d" (if (neg? cents) "-" "")
          (quot (abs cents) 100) (rem (abs cents) 100)))

what string does (money -5) return? Type it without quotes.

4. Testing, tooling and a complete project

CoreComputational

In the project, (shares 1001 ["a" "b" "c"]) splits 1001 cents three ways. How many cents does "b" get?

5. Testing, tooling and a complete project

CoreComputational

What is the value under "A" in the result of this call to the project's function?

(expense->deltas {:paid-by "A" :cents 900 :among ["A" "B" "C"]})

6. Testing, tooling and a complete project

CoreHuman

What are .cljc files and reader conditionals such as #?(:clj ... :cljs ...) for?

Choose one

7. Testing, tooling and a complete project

Warm-upHuman

Which tool would flag an unused let binding or a call with the wrong number of arguments, as you type?

Choose one

Further reading and resources