Getting http stub to work

I am using this library to stub http requests. I just followed the instructions from read me. But I get connection refused error

Execution error (ConnectException) at java.net.PlainSocketImpl/socketConnect (PlainSocketImpl.java:-2).
Connection refused (Connection refused)

This is the code. What am I doing wrong?

(stub/with-routes!
  {"/foo" {:status       200
           :content-type "application/json"
           :body         "{\"code\":\"SUCCESS\"}"}}
  (http/get "http://localhost/foo/"))

EDIT
Dug a bit deeper to check see the default port which turns out to be 65468. But still the same response

Did the readme’s examples work? It is a bit weird that the code here stubs /foo and then requests /foo/.

On the theory that you post here because you are interested in the opinions of generalists, I would venture to suggest (and the readme also hints of this) that the circumstances are unfortunate, when you need to intercept your program’s outgoing HTTP requests and divert them to a webserver your program runs on a random ephemeral port. Wrong way. Red blinky lights.

Hi. Not sure what the context is here. If you are trying to do this in a test, have you considered using with-redefs? Especially if you can isolate the network call in a function by itself ie

(ns xyz
  (:require [clj-http.client :as http])
  
(defn get-foo []
  (http/get "http://api.example.com/foo"))

and then in your test or elsewhere

(ns xyz-test
  (:require [xyz])

(with-redefs [xyz/get-foo (constantly {:status 200
                                       :content-type "application/json"
                                       :body "{\"code\":\"SUCCESS\"}"})]
   (xyz/get-foo))

You need to use uri from stub. stub starts a local server on a random port and you need to send requests to that server. Take a look at how they send a request in this example:

But then this does not use server at all.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.