Fixtures: setup and tear down for unit tests
Fixtures allow you to run code before and after tests, to set up the context in which tests should be run. Consider when fixtures should be run, especially fixtures that take a noticeable time to setup or tear down.
Organize tests with test selectors
Tests with fixtures may be slower to run so separate them by using a test selector, a piece of meta data attached to a
deftest definition. For example, add the
^:database meta data to test that require database fixtures (deftest ^:database db-bulk-upload). The test runner can be instructed to skip or focus on tests with specific meta data.
Defining a fixture
A fixture is a standard Clojure function which takes a function as an argument. The function passed as an argument is either an individual test or all tests in the namespace, depending on how the fixture is used.
(defn my-fixture [test-run] ;; Setup: define bindings, create state, etc. (test-run) ;; Run the relevant tests for the fixture (see `use-fixtures`) ;; Tear-down: reset state to a known value )
Requires for clojure.test fixtures
(ns domain.application-test (:require [clojure.test :refer [deftest is testing use-fixtures]]))
When to run fixtures
use-fixtures function defines when a fixture should be called when running the unit tests in each namespace. All Clojure unit test runners should support the
use-fixtures definitions when running the tests.
||Run the fixtures once for the namespace.|
||Run the fixtures for each `deftest** in the namespace|
Anonymous functions as fixtures
(use-fixtures :each (fn [f] #_setup... (f) #_teardown))
Example: development database
(defn database-reset-fixture "Setup: drop all tables, creates new tables Teardown: drop all tables SQL schema code has if clauses to avoid errors running SQL code. Arguments: test-function - a function to run a specific test" [test-function] (SUT/create-database) (test-function) (SUT/delete-database))
(use-fixtures :each database-reset-fixture)