I tried to find a way to stub calls to external services via WireMock
. WireMock
easily mocks any relative URL, but what if we want to intercept a REST call, which was sent from our node to some 3rd party service and return predefined response? Is there any possibility to do that?
What Is Stubbing? Stubbing is a technique that allows us to configure the HTTP response that is returned by our WireMock server when it receives a specific HTTP request. We can stub HTTP requests with WireMock by using the static givenThat() method of the WireMock class.
What is API Stubbing? The simplest of the three test doubles is the API stub. When a tester creates stubs, they're creating parts with minimal implementations of an interface. A stub always returns hardcoded data, or “canned” answers, to API calls made during individual tests.
WireMock is a tool that can mimic the behavior of an HTTP API and capture the HTTP requests send to that API. It allows us to: Configure the response returned by the HTTP API when it receives a specific request. Capture the incoming HTTP requests and write assertions for the captured HTTP requests.
I did a workaround by extracting the host as application configuration.
So if your application sends requests to:
http://thired-party-service.com/someEndPoint
You can extract the host as configuration param:
host=http://thired-party-service.com/
Now when you running in a test context fill the host param with same host as your WireMock server, for example:
host=http://localhost:8080/
Now you can use WireMock stubs as usual.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With