Because of tests should be stable and predictable, they shouldn’t depend on external services.
So this article will describe how we can mock all external requests.
First let’s make a little test module:
The trick is to register our own guzzle middleware. You can learn more about middlewares here. To register our middleware we need a services.yml file.
And our middleware.
This is pretty cool. The middleware runs before every request is executed. So at that time we can decide:
Is for the current request URL a mock response defined, return it.
Is this a local request, pass it by.
Otherwise throw an exception.
In our tests we just call addUrlResponse() to add the mocked responses.
Activate this functionality by adding your test module to the $modules property of your test class.
We added this functionality very recently to our Thunder tests to make them more stable.