如何使用clojure.test将一个值从夹具传递给测试?

pup*_*eno 14 testing clojure fixtures

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

Art*_*ldt 7

一些不错的选择是动态绑定和with-redefs.您可以从fixture中的测试命名空间绑定var,然后在测试定义中使用它:

core.clj:

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

 (defn foo [x]
  (inc x))
Run Code Online (Sandbox Code Playgroud)

测试/你好/ 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 Code Online (Sandbox Code Playgroud)

您可以通过比较直接调用测试(不使用fixture)来调用它来通过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}
Run Code Online (Sandbox Code Playgroud)

这种方法很有效,因为灯具会关闭它们运行的​​测试,尽管它们不能直接(通常)直接调用测试函数,因此使用闭包将信息传递给测试代码是有意义的.