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

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


一些好的选择是动态绑定和with-redefs 。 您可以将灯具中测试名称空间的var绑定到测试定义中,然后使用它:

core.clj:

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

 (defn foo [x]
  (inc x))

测试/你好/ 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)))))

您可以通过比较直接调用不使用灯具run-tests来通过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}

这种方法是有效的,因为fixtures会关闭他们运行的测试,尽管他们并没有直接(通常)直接调用测试函数,所以使用闭包将信息传递给测试代码是有意义的。


也许不是一个直接的答案,但是如果你的夹具是一个:each夹具,或者你可以容忍它是一个:each夹具,你可以删除并创建一个set-up函数返回相关状态并称之为第一个你的测试线,而不是使用夹具。 在某些情况下,这可能是最好的方法。

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

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

上一篇: How to pass a value from a fixture to a test with clojure.test?

下一篇: How to have a fixture loaded for Django tests in the test runner?