【发布时间】:2016-10-17 19:25:19
【问题描述】:
我使用 http-kit 作为服务器,使用来自 ring.middleware.json 的 wrap-json-body 来获取从客户端发送的字符串化 JSON 内容作为请求正文。我的core.clj 是:
; core.clj
; ..
(defroutes app-routes
(POST "/sign" {body :body} (sign body)))
(def app (site #'app-routes))
(defn -main []
(-> app
(wrap-reload)
(wrap-json-body {:keywords? true :bigdecimals? true})
(run-server {:port 8080}))
(println "Server started."))
当我使用lein run 运行服务器时,该方法可以正常工作。我正在对 JSON 进行字符串化并从客户端发送它。 sign 方法正确获取 json 为{"abc": 1}。
问题是在模拟测试期间。 sign 方法得到一个 ByteArrayInputStream ,我正在使用 json/generate-string 转换为在这种情况下失败的字符串。我尝试将处理程序包装在wrap-json-body 中,但它不起作用。这是我尝试过的测试用例core_test.clj:
; core_test.clj
; ..
(deftest create-sign-test
(testing "POST sign"
(let [response
(wrap-json-body (core/app (mock/request :post "/sign" "{\"username\": \"jane\"}"))
{:keywords? true :bigdecimals? true})]
(is (= (:status response) 200))
(println response))))
(deftest create-sign-test1
(testing "POST sign1"
(let [response (core/app (mock/request :post "/sign" "{\"username\": \"jane\"}"))]
(is (= (:status response) 200))
(println response))))
(deftest create-sign-test2
(testing "POST sign2"
(let [response (core/app (-> (mock/body (mock/request :post "/sign")
(json/generate-string {:user 1}))
(mock/content-type "application/json")))]
(is (= (:status response) 200))
(println response))))
(deftest create-sign-test3
(testing "POST sign3"
(let [response
(wrap-json-body (core/app (mock/request :post "/sign" {:headers {"content-type" "application/json"}
:body "{\"foo\": \"bar\"}"}))
{:keywords? true :bigdecimals? true})]
(is (= (:status response) 200))
(println response))))
所有失败并出现以下错误:
Uncaught exception, not in assertion.
expected: nil
actual: com.fasterxml.jackson.core.JsonGenerationException: Cannot JSON encode object of class: class java.io.ByteArrayInputStream: java.io.ByteArrayInputStream@4db77402
如何将 JSON 字符串作为主体传递给环模拟测试中的方法?
【问题讨论】:
标签: unit-testing clojure mocking ring http-kit