我正试图使用ring mock编写一个midje测试,以发布到解放者端点。我可以成功地为get请求编写一个测试,但我似乎无法将数据传递给post,我只能得到格式错误的响应。这是我掌握的代码的要点。
;; ====
; Resource
;; ====
(def users (atom [{:id 1 :name "User One"} {:id 2 :name "User Two"}]))
(defn malformed-users? [context]
(let [params (get-in context [:request :multipart-params])]
(and
(empty? (get params "id"))
(= (get-in context [:request :request-method]) :post))))
(defresource all-users []
:allowed-methods [:get :post]
:available-media-types ["application/json"]
:handle-ok (fn [_] {:users @users})
:malformed? (fn [context] (malformed-users? context))
:handle-malformed "You need to pass both a valid name and id"
:post! (fn [context]
(let [params (get-in context [:request :multipart-params])]
(swap! users conj {:id (bigint (get params "id")) :name (get params "name")})))
:handle-created (fn [_] {:users @users}))
(defroutes user-routes
(ANY "/users" [_] (all-users)))
;; ====
; Test
;; ====
(fact "Get request to users endpoint returns desired content"
(let [response (user-routes (mock/request :post "/users" {:id "3" :name "TestGuy"}))]
(:status response) => 201
(get-in response [:headers "Content-Type"]) => "application/json;charset=UTF-8"))
此代码存在一些问题。
首先,您的资源接受JSON,但您的代码使用多部分参数。您需要决定是接受"application/json"还是"multipart/form-data"。
假设您接受JSON。在这种情况下,您需要实际解析来自请求主体的数据。通常您在以下位置执行此操作:畸形?决策点。请参阅Liberator网站上的综合文档。
第三,您的mock请求需要包含一个内容类型,并将主体格式化为JSON。Ring Mock库非常简单;除非你告诉它,否则它猜不出你需要什么。
代码中还有一些其他奇怪的东西,比如(empty? (get params "id"))
。你真的希望你的"id"参数是一个集合吗?
我建议在尝试更复杂的资源之前,先看看Liberator的例子,试着让一些简单的东西发挥作用。