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

当使用clojure.test的use-fixture,有没有办法将fixture函数中的值传递给测试函数?


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.


Perhaps not a direct answer, but if your fixture was an :each fixture anyway, or you can tolerate it being an :each fixture, you can just cop out and create a set-up function returning the relevant state and call it as the first line of your test, instead of using a fixture. This may be the best approach for some circumstances.

(defn set-up [] (get-complex-state))

(deftest blah
   (let [state (set-up)]
     (frobnicate)
     (query state)
     (tear-down state)))
链接地址: http://www.djcxy.com/p/52310.html

上一篇: 无法解析Tycho项目中的Mockito依赖项

下一篇: 如何使用clojure.test将夹具中的值传递给测试?