Mocking APIs in Laravel Tests With Wiremock
Accounting for APIs while testing can be a confusing and sometimes painful process. Whether you are testing client-side components or server-side code, you must somehow mock or fake the request and response in your code.
The landscape of testing tools that ship with third-party HTTP client code is a mixed bag. In the Laravel ecosystem, we are fortunate to have testing capabilities built in to the Laravel HTTP Client, but what do you do about HTTP clients that don’t use the Laravel client? Packages could use Guzzle or cURL directly and may or may not include some way to fake API calls easily.The first thing that comes to mind is wrapping the original HTTP client in a service and mocking/faking the response:
You may have seen someone introduce a Guzzle middleware for the same purpose or, even worse, mocked Guzzle directly. Gross!
While mocking code via a service for a simple API call might be all you need, if you have more complex API usage in your application, you could stop mocking HTTP clients in code and use an HTTP mock server instead.
Enter Wiremock.
There are various HTTP mock servers on the market, but we will look specifically at Wiremock, a Java-based HTTP mock library. It includes first-party tooling for Java developers. However, it also provides a standalone runtime (JAR) and REST API we can utilize in PHP projects.We are just going to scratch the surface of everything Wiremock is capable of, but we will follow up with more tutorials in the future to dive deeper into features you’ll love.If you’re following along, you can also use PHPUnit; our code examples should translate easily as we work through the application.
Next, we are going to create a docker-compose.yaml file create an empty directory for default Wiremock mappings (we will cover those later) in the root of our project: