我想知道是否有广泛使用的模式或解决方案用于将出站http请求固定在clojure集成测试中(a la ruby's webmock)中。我希望能够在高级请求(例如,在设置功能中),而无需将我的每个测试包装在(with-fake-http [] ...)
之类的东西或必须诉诸依赖性注入中。
这是否是动态VAR的好用例?我想我可以在设置步骤中访问有问题的名称空间,并将副作用函数设置为无害的匿名函数。但是,这感觉很笨拙,我不喜欢更改我的应用程序代码以适应我的测试的想法。(这也不比上面提到的解决方案好很多。)
交换包含假函数的特定于测试的NS是否有意义?在我的测试中有没有干净的方法?
我前一段时间处于类似情况,我找不到满足我需求的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))))))
您可以使用环/综合框架看到一个很好的示例:
> 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
。
完整的文档在Clojuredocs。