我在Clojure中有一个函数可以通过rand
生成随机数:
core.clj
:
(ns my-lib.core)
(def my-rand rand)
(defn my-fn []
(take 3 (repeatedly my-rand)))
我想测试它,但很难,因为我不知道会发生什么。有没有办法可以重新绑定core/my-rand
,这样可以让测试变得更容易?像这样:
core_test.clj
:
(ns my-lib.core-test
(:require [clojure.test :refer :all]
[my-lib.core as core]))
; i'd like to re-bind the my-rand function here to make testing easier, but this doesn't work
(def core/my-rand (constantly 1))
(deftest my-fn
(is (= (core/my-fn) '(1 1 1))))
或者,有没有更惯用的方法呢?
答案 0 :(得分:3)
您需要with-redefs
:
http://clojuredocs.org/clojure_core/clojure.core/with-redefs
(deftest my-fn-test
(with-redefs [core/my-fn (constantly 1)]
(is (= (repeatedly 3 core/my-fn) '(1 1 1)))))