我使用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