我使用 http-kit 作为服务器,使用wrap-json-body
fromring.middleware.json
来获取从客户端发送的字符串化 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}
.
问题是在模拟测试期间。sig
n 方法得到 a 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 字符串作为主体传递给环模拟测试中的方法?