Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a value from a fixture to a test with clojure.test?

When using clojure.test's use-fixture, is there a way to pass a value from the fixture function to the test function?

like image 798
pupeno Avatar asked Jul 30 '15 22:07

pupeno


People also ask

How do you run a Clojure test?

You can run tests by using the cljs. test/run-tests macro. This may be done in your REPL or at the end of your file. If you have many test namespaces it's idiomatic to create a test runner namespace which imports all of your test namespaces and then invokes run-tests .

What is fixture in unit test?

A test fixture is a fixed state of a set of objects used as a baseline for running tests. The purpose of a test fixture is to ensure that there is a well known and fixed environment in which tests are run so that results are repeatable.

What is test fixture in selenium?

This is the attribute that marks a class that contains tests and, optionally, setup or teardown methods. There are a few restrictions on a class that is used as a test fixture. It must be a publicly exported type. It must have not be abstract. It must have a default constructor.

What is a test fixture class?

A Test Fixture is the class that contain the tests we want to run. We typically write one test fixture for each class we want to test. As a convention we name the test fixture <Class to be tested>Tests.


1 Answers

A couple of good choices are dynamic binding and with-redefs. You could bind a var from the test namespace in the fixture and then use it in a test definition:

core.clj:

(ns hello.core
  (:gen-class))

 (defn foo [x]
  (inc x))

test/hello/core.clj:

(ns hello.core-test
  (:require [clojure.test :refer :all]
            [hello.core :refer :all]))

(def ^:dynamic *a* 4)

(defn setup [f]
  (binding [*a* 42]
    (with-redefs [hello.core/foo (constantly 42)]
      (f))))

(use-fixtures :once setup)

(deftest a-test
  (testing "testing the number 42"
    (is (= *a* (foo 75)))))

You can tell that it works by comparing calling the test directly, which does not use fixtures, to calling it through run-tests:

hello.core-test> (a-test)

FAIL in (a-test) (core_test.clj:17)
testing the number 42
expected: (= *a* (foo 75))
  actual: (not (= 4 76))
nil
hello.core-test> (run-tests)

Testing hello.core-test

Ran 1 tests containing 1 assertions.
0 failures, 0 errors.
{:test 1, :pass 1, :fail 0, :error 0, :type :summary}

This approach works because fixtures close over the tests they run, though they don't get to actually make the calls to the test functions directly (usually) so it makes sense to use closures to pass information to the test code.

like image 143
Arthur Ulfeldt Avatar answered Oct 17 '22 12:10

Arthur Ulfeldt