可以使用環/的Compojure框架看到一個很好的例子:
> lein new compojure sample
> cat sample/test/sample/handler_test.clj
(ns sample.handler-test
(:require [clojure.test :refer :all]
[ring.mock.request :as mock]
[sample.handler :refer :all]))
(deftest test-app
(testing "main route"
(let [response (app (mock/request :get "/"))]
(is (= (:status response) 200))
(is (= (:body response) "Hello World"))))
(testing "not-found route"
(let [response (app (mock/request :get "/invalid"))]
(is (= (:status response) 404)))))
更新
對於出站HTTP調用,您可能會發現with-redefs
有用:
(ns http)
(defn post [url]
{:body "Hello world"})
(ns app
(:require [clojure.test :refer [deftest is run-tests]]))
(deftest is-a-macro
(with-redefs [http/post (fn [url] {:body "Goodbye world"})]
(is (= {:body "Goodbye world"} (http/post "http://service.com/greet")))))
(run-tests) ;; test is passing
在這個例子中,原函數post
返回「Hello world」。在單元測試中,我們使用返回「再見世界」的存根函數暫時覆蓋post
。
完整文檔is at ClojureDocs。
大多數(所有?)clojure http庫都將請求和響應表示爲映射,因此您可以直接在測試中構建這些請求而不會嘲笑。 – Lee
依賴注入有什麼問題?你是否在自己的職位上使用硬編碼的網址?因爲你不應該這樣做,那很糟糕,mkay。 –