with-redefs不会重新定义我的函数

时间:2015-12-22 13:46:25

标签: unit-testing clojure compojure

我有一个测试:

(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)))

所以,基本上我想停止对数据库命名空间的调用,但是我结束了在胖数据库中的upp异常堆栈跟踪......

有什么问题?

2 个答案:

答案 0 :(得分:1)

with-redefs-fn获取绑定图,而不是矢量图。请注意,clojuredocs中的示例使用#'读取器宏来引用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))))))

答案 1 :(得分:0)

请查看with-redefs它应符合您的使用情况。

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