【问题标题】:with-redefs doesn't redefine my functionwith-redefs 不会重新定义我的功能
【发布时间】:2016-03-28 19:19:00
【问题描述】:

我有一个测试:

(ns gui-proxy.handler-test
  (:require [clojure.test :refer :all]
            [ring.mock.request :as mock]
            [gui-proxy.handler :as handler]))

(deftest test-app
  (testing "not-found route"
        (with-redefs-fn [handler/log-request  (fn [type url] (str ""))]
          (let [response (handler/app (mock/request :get "/invalid"))]
            (is (= (:status response) 404))))))

以及正在测试的代码:

(ns gui-proxy.handler
  (:require [compojure.core :refer :all]
            [compojure.route :as route]
            [ring.middleware.defaults :refer [wrap-defaults site-defaults]]
            [clj-http.client :as client]
            [gui-proxy.db :as db]))

(defn log-request [type url]
    (db/insert-request-info type url))

(defn log-error []
    (log-request ":fail" "fail"))
    "gui-proxy - File not found")

(defroutes app-routes
    (route/not-found (log-error)))

所以,基本上我想停止对数据库命名空间的调用,但我最终陷入了一个胖数据库异常堆栈跟踪......

怎么了?

【问题讨论】:

  • 您的log-error 函数看起来像复制&粘贴&编辑错误。

标签: unit-testing clojure compojure


【解决方案1】:

with-redefs-fn 采用绑定映射,而不是向量。请注意,clojuredocs 上的示例使用#' reader 宏来引用 Var,所以总结一下您可以尝试

(deftest test-app
  (testing "not-found route"
        (with-redefs-fn {#'handler/log-request  (fn [type url] (str ""))}
          (let [response (handler/app (mock/request :get "/invalid"))]
            (is (= (:status response) 404))))))

【讨论】:

    【解决方案2】:

    看看with-redefs,它应该符合你的用法。

    http://clojuredocs.org/clojure.core/with-redefs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-07
      • 1970-01-01
      • 2023-04-07
      • 2014-02-13
      • 1970-01-01
      • 1970-01-01
      • 2022-11-29
      • 2016-04-15
      相关资源
      最近更新 更多