2017-03-01 27 views
1

我想知道在Clojure集成測試(Ruby的webmock)中是否有廣泛使用的模式或解決方案將出站HTTP請求存儲到第三方。我希望能夠在高級別存根請求(例如,在一個設置函數中),而不必將我的每個測試都包含在(with-fake-http [] ...)之類的東西中,或者不得不依賴於依賴注入。在Clojure測試中存儲HTTP請求的策略

這是一個很好的動態var的用例嗎?我想我可以在設置步驟中進入有問題的命名空間,並將副作用函數設置爲無害的匿名函數。然而,這感覺很沉重,我不喜歡改變我的應用程序代碼以適應我的測試。 (它也不比上面提到的解決方案好多少。)

交換包含假函數的測試專用ns是否合理?有沒有一種乾淨的方式在我的測試中做到這一點?

+1

大多數(所有?)clojure http庫都將請求和響應表示爲映射,因此您可以直接在測試中構建這些請求而不會嘲笑。 – Lee

+0

依賴注入有什麼問題?你是否在自己的職位上使用硬編碼的網址?因爲你不應該這樣做,那很糟糕,mkay。 –

回答

1

我曾經有過類似的情況,但是我找不到任何滿足我需求的Clojure庫,所以我創建了自己的庫,名爲Stub HTTP。用法示例:

(ns stub-http.example1 
    (:require [clojure.test :refer :all] 
      [stub-http.core :refer :all] 
      [cheshire.core :as json] 
      [clj-http.lite.client :as client])) 

(deftest Example1 
    (with-routes! 
     {"/something" {:status 200 :content-type "application/json" 
        :body (json/generate-string {:hello "world"})}} 
     (let [response (client/get (str uri "/something")) 
      json-response (json/parse-string (:body response) true)] 
     (is (= "world" (:hello json-response)))))) 
+1

謝謝你。我會調查你的圖書館並跟進。 :) – pdoherty926

0

可以使用環/的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

+0

謝謝你。我已經更新了我的問題,以更具體地說明我要存根據的請求類型。特別是,我的應用程序向第三方發出的出站請求。 – pdoherty926

+0

再次感謝。我會試驗你的建議和後續行動(可能會有幾天)。乍一看,與webmock這樣的解決方案相比,這是相當笨拙的,因爲我需要深入瞭解嵌套函數調用將會做什麼。 – pdoherty926