使用 clojure.test's use-fixture 时, 有没有办法将值从 fixture 函数传递到测试函数?
最佳答案
两个不错的选择是动态绑定(bind)和with-redefs
。您可以从 fixture 中的测试命名空间绑定(bind)一个 var,然后在测试定义中使用它:
核心.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
调用它来判断它是否有效:
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 关闭了它们运行的测试,尽管它们实际上并没有直接(通常)直接调用测试函数,所以使用闭包来传递是有意义的测试代码的信息。
关于testing - 如何使用 clojure.test 将值从 fixture 传递到测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31735423/