我使用http-kit作爲wrap-json-body
來自ring.middleware.json
的服務器,以獲取從客戶端發送的字符串化JSON內容作爲請求主體。我core.clj
是:如何使用環模擬請求模擬測試POST請求與身體爲JSON?
; 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字符串化並從客戶端發送。標誌方法正確得到json,如{"abc": 1}
。
問題是在模擬測試過程中。 sig
n方法得到一個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: [email protected]
我如何傳遞一個JSON字符串作爲身體的方法在環模擬測試?
非常感謝你! 'sign'方法正確地獲取JSON。我一直在努力幾個小時才能做到這一點。 – boring