@@ -234,11 +234,63 @@ A proxy can be specified by setting the Java properties:
234234` <scheme>.proxyHost ` and ` <scheme>.proxyPort ` where ` <scheme> ` is the client
235235scheme used (normally 'http' or 'https').
236236
237- ## Faking clj-http responses
237+ ## Mocking clj-http responses
238238
239- If you need to fake clj-http responses (for things like testing and
240- such), check out the
241- [ clj-http-fake] ( https://github.com/myfreeweb/clj-http-fake ) library.
239+ Mocking responses from the clj-http-lite client in tests is easily accomplished with e.g. ` with-redefs ` :
240+
241+ ``` clojure
242+ (defn my-http-function []
243+ (let [response (client/get " https://example.org" )]
244+ (when (= 200 (:status response))
245+ (:body response))))
246+
247+ (deftest my-http-function-test
248+ (with-redefs [client/get (fn [_] {:status 200 :headers {" content-type" " text/plain" } :body " OK" })]
249+ (is (= (my-http-function ) " OK" ))))
250+ ```
251+
252+ More advanced mocking may be performed by matching attributes in the ` request ` , like the ` mock-response ` function below.
253+
254+ ``` clojure
255+ (ns http-test
256+ (:require [clojure.data.json :as json]
257+ [clojure.test :refer [deftest is testing]]
258+ [clj-http.lite.client :as client]))
259+
260+ (defn send-report [data]
261+ (:body (client/post " https://example.com/reports" {:body data})))
262+
263+ (defn get-users []
264+ (json/read-str (:body (client/get " https://example.com/users" ))))
265+
266+ (defn get-admin []
267+ (let [response (client/get " https://example.com/admin" )]
268+ (if (= 200 (:status response))
269+ (:body response)
270+ " 403 Forbidden" )))
271+
272+ (defn mock-response [{:keys [url method body] :as request}]
273+ (condp = [url method]
274+ [" https://example.com/reports" :post ]
275+ {:status 201 :headers {" content-type" " text/plain" } :body (str " created: " body)}
276+
277+ [" https://example.com/users" :get ]
278+ {:status 200 :headers {" content-type" " application/json" } :body (json/write-str [" joe" " jane" " bob" ])}
279+
280+ [" https://example.com/admin" :get ]
281+ {:status 403 :headers {" content-type" " text/plain" } :body " forbidden" }
282+
283+ (throw (ex-info " unexpected request" request))))
284+
285+ (deftest send-report-test
286+ (with-redefs [client/request mock-response]
287+ (testing " sending report"
288+ (is (= (send-report {:balance 100 }) " created: {:balance 100}" )))
289+ (testing " list users"
290+ (is (= (get-users ) [" joe" " jane" " bob" ])))
291+ (testing " access admin page"
292+ (is (= (get-admin ) " 403 Forbidden" )))))
293+ ```
242294
243295## GraalVM Native Image Tips
244296
0 commit comments