Fixtures

Fixtures allow you to run code before and after tests, to set up the context in which tests should be run.

A fixture is just a function that calls another function passed as an argument. It looks like this:

(defn my-fixture [f]
  ;;Perform setup, establish bindings, whatever.
  (f)  ;;Then call the function we were passed.
  ;;Tear-down / clean-up code here.
 )

There are two way of registering fixture in clojure: :each and :once. We use use-fixtures to register fixtures.

One time fixture

The fixture registered with :once will be called before any tests are run and it will be pased a function to call that will invoke all the tests. You can have a fixture that only runs once, around all the tests in the namespace.

(defn one-time-setup [])
(defn one-time-teardown [])

(defn one-time-fixture
  [f]
  (one-time-setup)
  (f)
  (one-time-teardown))

; One time fixture: use `:once` meta.
(use-fixtures :once one-time-fixture)

(testing "case 1")
(testing "case 2")

Each fixture

The fixture registered with :each will be called before each tests are run and it will be passed a function to call that will invoke every test. Fixtures are run repeatedly, once for each test, they can be attached to the current namespace like this,

(defn each-setup [])
(defn each-teardown [])

(def each-fixture
  [f]
  (each-setup)
  (f)
  (each-teardown))

(use-fixtures :each each-fixture)

Real World Example

(defn test-client-fixture
  [f]
  (with-client (client-factory "localhost:11211")
    (try
      (f)
      (finally (spy/flush)))))

(clojure.test/use-fixtures :once test-client-fixture)

(deftest test-set-get
  (testing "Simple Set and then Get."
     (spy/set "set-get" 1 3600)
     (is (= 1 (spy/get "set-get")))))

Source: spymemcat