【问题标题】:What is the difference between with-redefs and with-redefs-fn in Clojure?Clojure 中的 with-redefs 和 with-redefs-fn 有什么区别?
【发布时间】:2017-09-07 00:21:26
【问题描述】:

我想了解with-redefs 和with-redefs-fn 之间的区别。

具体的例子有助于理解 fns 的行为。

【问题讨论】:

    标签: clojure mocking clojurescript


    【解决方案1】:

    它们基本相同,主要区别在于with-redefs 允许您显式地写出正文(就像在let 中一样),而with-redefs-fn 需要一个函数作为参数,因此您可能需要将您想要的内容包装在 lambda 中。此外,with-redefs 允许您使用矢量提供绑定(同样,如let),而with-redefs-fn 需要地图。我认为这两种差异都只是表面现象。

    例如

    (with-redefs [http/post (fn [url] {:body "Goodbye world"})]
      (is (= {:body "Goodbye world"} (http/post "http://service.com/greet"))))
    

    对比

    (with-redefs-fn {#'http/post (fn [url] {:body "Goodbye world"})}
          (fn [] (is (= {:body "Goodbye world"} (http/post "http://service.com/greet")))))
    

    实际上,with-redefs 是根据with-redefs-fn 定义的,基本上只是在将所有内容传递给with-redefs-fn 之前将主体包装在一个匿名函数中:https://github.com/clojure/clojure/blob/e3c4d2e8c7538cfda40accd5c410a584495cb357/src/clj/clojure/core.clj#L7404

    【讨论】:

      【解决方案2】:

      我会忽略with-redefs-fn 而只使用with-redefs,因为它更简单并且具有相同的功能。另外,请注意 #'http/post 表示法要求您使用 http/post 的 var,而不是函数本身。

      有关 Clojure var 工作原理的说明,请参阅此问题:When to use a Var instead of a function? 它类似于 C 指针。

      在clojure中,当你看到foo时,它是一个符号。当您看到#'foo 时,它是(var foo) 的快捷方式,它是一种“特殊形式”(即Clojure 内置,而不是常规函数),它返回foo 指向的var。 var 又指向foo 的值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-04-07
        • 2016-03-28
        • 2021-12-05
        • 1970-01-01
        • 2012-08-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多