【问题标题】:Compojure app not playing well with with-redefsCompojure 应用程序无法与 with-redefs 配合使用
【发布时间】:2012-08-29 13:26:23
【问题描述】:

我正在编写一个 Compojure 应用程序,并正在使用 clj-webdriver 以图形方式对其进行测试。我正在尝试使用with-redefs 来模拟从持久性中提取数据以仅返回预设值的函数,但它忽略了我的函数覆盖。我知道with-redefs 在变量方面起作用,但它仍然不起作用:

project.clj 相关部分:

(defproject run-hub "0.1.0-SNAPSHOT"                                                                                                                        
  :main run-hub.handler/start-server)

handler.clj:

(ns run-hub.handler
  (:require [compojure.core :refer :all]
            [compojure.handler :as handler]
            [compojure.route :as route]
            [ring.adapter.jetty :refer :all]
            [run-hub.controllers.log-controller :as log-controller]))

(defroutes app-routes
  (GET "/MikeDrogalis/log" [] (log-controller/mikes-log))
  (route/resources "/")
  (route/not-found "Not Found"))

(def app (handler/site #'app-routes))

日志控制器.clj:

(ns run-hub.controllers.log-controller                                                                                                                      
  (:require [run-hub.views.log :as views]
            [run-hub.persistence :as persistence]))

(defn mikes-log []
  (views/mikes-log (persistence/mikes-log)))

persistence.clj

(ns run-hub.persistence                                                                                                                                     
  (require [clj-time.core :as time]
           [run-hub.models.log :as log]))

(defn mikes-log [] [])

最后,我的图形测试 - 试图覆盖 mikes-log 并失败:

(fact
 "It has the first date of training as August 19, 2012"
 (with-redefs [persistence/mikes-log (fn [] (one-week-snippet))]
   (to (local "/MikeDrogalis/log"))
   (.contains (text "#training-log") "August 19, 2012"))                                                                                                    
 => true)

其中one-week-snippet 是一个返回一些样本数据的函数。 (定义启动服务器 [] (run-jetty (var app) {:port 3000 :join?false}))

【问题讨论】:

  • 我猜测试调用了 Web 服务器,这是一个单独的进程,因此您在测试(客户端)代码中的重新定义不会影响服务器代码上的 var 绑定
  • 似乎有可能,是的。我被难住了。
  • 使用 clj-webdriver 的假设是您正在编写高级集成测试。在我看来,这些测试应该锻炼整个堆栈,所以在这里存根一个函数对我来说没有什么意义。假设您的各个命名空间已经过单元测试,为什么要在集成测试中存根这个函数?

标签: clojure compojure ring


【解决方案1】:

我可以在 clj-webdriver 测试中使用 with-redefs 执行以下操作:

(defn with-server
  [f]
  (let [server (run-jetty #'APP {:port 0 :join? false})
        port (-> server .getConnectors first .getLocalPort)]
    (binding [test-port port]
      (try
        (println "Started jetty on port " test-port)
        (f)
        (finally
          (.stop server))))))

(use-fixtures :once with-server)

然后所有测试都有自己的码头,这似乎在运行 这样with-redefs 工作的方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-07
    • 2023-04-07
    • 2010-11-07
    • 2014-06-17
    • 2012-03-06
    • 2015-09-02
    • 2015-05-05
    • 1970-01-01
    相关资源
    最近更新 更多