在Clojure中重新绑定随机数生成器 [英] Re-bind a Random Number Generator in Clojure
本文介绍了在Clojure中重新绑定随机数生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Clojure中有一个函数,通过 rand
生成随机数:
I've got a function in Clojure which generates random numbers via rand
:
core.clj
:
(ns my-lib.core)
(def my-rand rand)
(defn my-fn []
(take 3 (repeatedly my-rand)))
我想测试一下,但很难,因为我不知道该怎么做。有没有办法,我可以重新绑定 core / my-rand
,使它使测试更容易?像这样:
I'd like to test it, but it's hard since I don't know what to expect. Is there a way that I could re-bind core/my-rand
such that it makes testing easier? Something like this:
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))))
推荐答案
您需要 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)))))
这篇关于在Clojure中重新绑定随机数生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文