0

例如,我知道with-redefs在测试某些东西时如何使用 stub 变量。我想知道是否可以将重新定义仅保留在代码的直接主体中,这样它就不会影响任何随后调用的函数。例如:

(defn foo [] (println "foo")

(with-redefs [println (constantly nil)]
    (println "bar")
    (foo))

什么都不打印,但如果可以做我所描述的事情,我们会看到只打印fooprintln ,因为它会在被调用的 function 中保留其原始值foo。这是可能吗?

4

1 回答 1

3

你想要的只是这里的相反with-redefs:简单的旧词法阴影:

(defn foo [] (println "Foo you."))

(println "to Foo, or not to Foo...")
(let [println (constantly nil)]
  (println "Foo me not.")
  (foo))
(println "...that is the question.")

结果:

to Foo, or not to Foo...
Foo you.
...that is the question.
于 2019-11-08T16:41:08.900 回答