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

Posted

技术标签:

【中文标题】如何使用 clojure.test 将值从夹具传递到测试?【英文标题】:How to pass a value from a fixture to a test with clojure.test? 【发布时间】:2015-10-22 11:57:45 【问题描述】:

在使用clojure.test's use-fixture时,有没有办法将值从fixture函数传递给test函数?

【问题讨论】:

【参考方案1】:

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

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)))))

您可以通过比较直接调用测试(不使用固定装置)与通过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 关闭了它们运行的​​测试,尽管它们实际上并没有(通常)直接调用测试函数,因此使用闭包来传递是有意义的测试代码的信息。

【讨论】:

【参考方案2】:

也许不是一个直接的答案,但是如果您的灯具无论如何都是:each 灯具,或者您可以容忍它是:each 灯具,您可以直接退出并创建一个set-up 函数返回相关状态和将其称为测试的第一行,而不是使用夹具。在某些情况下,这可能是最好的方法。

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

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

【讨论】:

以上是关于如何使用 clojure.test 将值从夹具传递到测试?的主要内容,如果未能解决你的问题,请参考以下文章

如何将值从 tableview 传递到 collectionview

如何将值从python传递给c++并返回?

如何将值从 javascript 函数传递到 django 视图

如何使用会话将值从一个php页面传递到另一个页面

如何将值从片段/活动传递到 xml?

如何将值从主传递到对话框