wiremock to mock public backend response

690 Views Asked by At

I am testing on an app that is making calls to a public backend.

I want to use wiremock to mock reponses from the public backends.

I was looking at something like

  1. the app makes a request to api.example.com which is forced through the wiremock proxy on localhost:<port>
  2. wiremock matches the URL based on the rules I provide and returns a mock response

The only examples I could find map localhost requests to real backends or mock responses to localhost.

1

There are 1 best solutions below

0
On

If I'm understanding your question, the app behaves as follows:

  • App sends request to your backend
  • Your backend responds with a forwarding request to a public backend
  • App sends request to public backend
  • Public backend responds

As far as I'm aware WireMock can only achieve this if you mock out the response from your backend, and have that response's forwarding request point to another mocked out response. WireMock only knows to redirect and proxy when requests are made to WireMock. WireMock does not behave as a man-in-the-middle proxy, listening to all requests made (regardless of url) and selectively returning mocked responses. WireMock only knows to proxy/forward/respond when you hit WireMock directly. So you'd need to have something like...

{
    "request" : {
        "url" : "/my-backend",
        "method": GET
    }, 
    "response" : {
        "status" : 302,
        "headers" : {
            "location" : "/public-backend"
        }
    }
}

Which would return a forwarding request to the /public-backend url. (Depending on what your actual API looks like when it returns that forwarding request, the above response may not be accurate.) And then you'd need to mock out what that request/response mapping looks like

{
    "request" : {
        "url" : "/public-backend",
        "method" : "GET"
    },
    "response" : {
        // response
    }
}

Depending on what you are using to run your tests, it is probably better to utilize an existing intercept/proxy functionality that the runner has to listen for requests to certain urls and return a mocked response that way. For example, TestCafe can intercept HTTP requests and return your custom responses. If you went about testing this way, then you'd be able to only have to mock out the response from the public API, and not from your backend as well.