Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 36 ยท Tooling and Interop

Testing, spec and REPL-Driven Development

Test and validate Clojure code: clojure.test with deftest, is, testing and fixtures, clojure.spec for data validation and generative testing, and the REPL-driven workflow.

Clojure programmers test in three complementary ways. The REPL gives instant feedback while you write code. clojure.test (built in) holds regression tests that run in CI. clojure.spec describes the shape of your data so you can validate it, explain failures and generate test data. This lesson covers all three.

REPL-driven development

A REPL (read-eval-print loop) is not just a console you type into: it is a live connection to your running program. In an editor with a Clojure plugin (Calva, CIDER, Cursive), you place the cursor on a form and press a key to evaluate it in the running process. You build the program in small steps, check each function with real data as you write it, and never restart.

A typical loop:

  1. Evaluate a small expression to see data: (slurp "data.csv").
  2. Write a function, evaluate it, call it with an example: (parse-line "a,b").
  3. Save a working example in a (comment ...) block next to the function:
CLOJURE
(defn parse-line [s]
  (clojure.string/split s #","))

(comment
  (parse-line "a,b,c")        ;=> ["a" "b" "c"]
  (parse-line "")             ;=> [""]
  )

A (comment ...) form is never evaluated at load time, so it is a safe notebook of examples. Other REPL habits: use (require '[my-app.core :as core] :reload) to pick up edits, (doc map) and (source map) to read documentation and code, (apropos "split") to search names, and *1, *2, *e for recent results and the last exception.

clojure.test

Tests are ordinary functions defined with deftest. Assertions use the is macro, which shows both the expression and the values when it fails.

CLOJURE
(ns my-app.core-test
  (:require [clojure.test :refer [deftest testing is are use-fixtures]]
            [my-app.core :as core]))

(deftest greet-test
  (testing "capitalizes the name"
    (is (= "Hello, Ana!" (core/greet "ana"))))
  (testing "handles empty input"
    (is (= "Hello, !" (core/greet "")))))

(deftest math-test
  (are [x y expected] (= expected (+ x y))
    1 2 3
    0 0 0
    -1 1 0)
  (is (thrown? ArithmeticException (/ 1 0)))
  (is (thrown-with-msg? ArithmeticException #"Divide" (/ 1 0))))
  • testing labels a group so failures say which part failed.
  • are runs one template over a table of rows, ideal for input/output cases.
  • thrown? and thrown-with-msg? check exceptions.
  • (is (= expected actual)) gives a readable diff; remember the conventional order is expected first.

Run them with lein test, clj -M:test (using the test-runner alias from the tooling lesson), or from the REPL: (clojure.test/run-tests 'my-app.core-test).

Fixtures

Fixtures wrap tests with setup and teardown:

CLOJURE
(def ^:dynamic *db* nil)

(defn with-db [f]
  (binding [*db* (atom {})]
    (f)))   ; run the tests

(use-fixtures :each with-db)    ; around every test

:once runs once per namespace (such as starting a server); :each runs around every test.

Testing tips

Write mostly pure functions; they need no fixtures. Keep side effects at the edges and test them with small stand-ins, for example passing an atom instead of a real database. For mocks, with-redefs temporarily replaces a var: (with-redefs [http/get (fn [_] {:status 200})] ...).

clojure.spec

clojure.spec.alpha (spec) describes data with predicates and regex-like specs, and builds on that:

CLOJURE
(require '[clojure.spec.alpha :as s])

(s/def ::name  (s/and string? #(<= 1 (count %) 50)))
(s/def ::age   (s/int-in 0 150))
(s/def ::email (s/and string? #(re-matches #".+@.+\..+" %)))
(s/def ::user  (s/keys :req-un [::name ::age] :opt-un [::email]))

(s/valid? ::user {:name "Ana" :age 30})       ;=> true
(s/valid? ::user {:name "" :age 30})          ;=> false
(s/explain ::user {:name "Ana" :age 200})
; 200 - failed: (int-in-range? 0 150 %) in: [:age] at: [:age] spec: :user/age
(s/explain-data ::user {:name "Ana"})         ; data version, for programs

Specs are named with namespaced keywords. s/keys checks that required keys exist and that every key that has a spec conforms. Besides s/and, there are s/or, s/coll-of, s/tuple, s/nilable and s/cat/s/*/s/+ for sequence structure.

Function specs with s/fdef describe a function's arguments and return value, and clojure.spec.test.alpha can instrument them (check arguments during development) or generate tests:

CLOJURE
(s/fdef core/greet
  :args (s/cat :name ::name)
  :ret  string?)

Generative testing. Each spec can generate random values that satisfy it, via test.check: (gen/sample (s/gen ::user)). With stest/check or clojure.test.check's defspec, you state a property and the system tries hundreds of random inputs, shrinking failures to a minimal case. A property example: "reversing a vector twice gives the original."

CLOJURE
(require '[clojure.test.check.generators :as gen]
         '[clojure.test.check.properties :as prop]
         '[clojure.test.check.clojure-test :refer [defspec]])

(defspec reverse-twice 100
  (prop/for-all [v (gen/vector gen/small-integer)]
    (= v (reverse (reverse v)))))

Malli is a popular alternative to spec (data-driven schemas, often friendlier errors). The ideas are identical: describe the data once and reuse it for validation, explanation and generation.

Try it: a tiny test runner

This stand-in implements deftest, is, testing and are so you can see how a test framework collects failures and reports them.

JS deftest and is

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Try it: spec-like validation and generation

JS Validate, explain and generate

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a (comment ...) form do in Clojure source?

    comment returns nil without evaluating its body, so it is the standard place for a scratchpad of examples.
  2. 2. What does are do in clojure.test?

    (are [x y] (= y (inc x)) 1 2 2 3) expands into one is per row.
  3. 3. What does s/valid? return?

    s/valid? is a boolean check; s/explain prints why a value fails and s/conform returns the parsed value or :clojure.spec.alpha/invalid.
  4. 4. What is the benefit of generative (property-based) testing?

    Randomized inputs find edge cases you did not think of, and shrinking reports a minimal counterexample.

Summary

  • REPL-driven development means evaluating forms in a live process; keep examples in (comment ...) blocks.
  • clojure.test gives deftest, is, testing, are, thrown?, fixtures and with-redefs.
  • clojure.spec describes data (s/def, s/keys, s/and), validates it (s/valid?), explains failures and specs functions (s/fdef).
  • Specs generate data for property-based tests with test.check.
  • Pure functions are the easiest to test; keep effects at the edges.

Next: Project: Word Frequency Analyzer