Reputation: 26008
I've built a library in clojure which sends/receive HTTP request, it's a client for some REST API web service. How can I test? I believe, my tests should send/receive real requests/responses. Then how can I test it? Firstly, I mean unit testing, then others.
Upvotes: 1
Views: 362
Reputation: 2824
@munk's assumption of:
I'm assuming you're not writing your own http library from scratch and are instead using clj-http or something.
If this isn't the case and you do actually want to test the inner working of the library you've created to ensure it's doing the right thing, web services such as postman-echo can be used. Alternatively you can host your own server and test against that on the localhost.
Upvotes: 0
Reputation: 12983
Suppose you have some library with a function does a transformation and sends the request:
(defn make-request [url data]
(http/post url data)
(defn transform [x y z]
{:x (* x x)
:y (* y y)
:z (* z z)})
(defn f [x y z]
"""f is the library function you want to expose as the client"""
(make-request "/api/v1/foo" (transform x y z))
You don't want to actually make http requests and responses when writing unit tests. They should be fast, and not depend on anything except the functional correctness of your code. So relying on a network connection and the service you're talking to being up are right out.
(with-redefs [http/post (fn [url data]
(is (= url "/api/v1/foo"))
(is (= data {:x 1 :y 4 :z 9})))]
(f 1 2 3)
I'm assuming you're not writing your own http library from scratch and are instead using clj-http or something. If it's a reliable library, we can make some assumptions about it working within our tests.
So, the only thing missing from the above test is to verify that you're actually calling the endpoint you're intending to with data as the client expects it.
You can demonstrate this by actually using your client library to make a call and verifying that the response you get back is correct. Or, if you have access to the target provider, you can write consumer driven contract tests.
Upvotes: 2