繁体   English   中英

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

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

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

一些不错的选择是动态绑定和with-redefs 您可以从fixture中的测试命名空间绑定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)))))

您可以通过比较直接调用测试(不使用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}

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

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

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

(deftest blah
   (let [state (set-up)]
     (frobnicate)
     (query state)
     (tear-down state)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM