Matthias Noback has continued his series about "mocking the edges" in your unit testing with this new post. In it, he talks about mocking "the network", those places where your application reaches out to external services to access data or perform other operations.
In this series, we've discussed several topics already. We talked about persistence and time, the filesystem and randomness. The conclusion for all these areas: whenever you want to "mock" these things, you may look for a solution at the level of programming tools used (use database or filesystem abstraction library, replace built-in PHP functions, etc.). But the better solution is always: add your own abstraction.[...] The same really is true for the network. You don't want your unit tests to rely on a network connection, or a specific web service to be up and running. [...] The smarter solution again is to introduce your own interface, with its own implementation, and its own integration test. [...] Though this solution would be quite far from traditional mocking I thought it would be interesting to write a bit more about it, since there's also a lot to say.
In his example he shows the use of a file_get_contents
call to fetch stock information. He introduces a ExchangeRateService
interface with a getFor
method to provide structure for the "wrapper" around the network call. He then covers the idea of an "anti-corruption layer" to change up the interface to use models instead of just a string value (code included). He ends the post talking about the inversion of the dependency - the option to have a job pull the value out-of-band and then have the application use that value.