In a new post to his site Tomas Votruba shows you how to make your unit test mocks better with an easier and clearer way to use them. This simplification makes use of something PHP itself is already able to do: create anonymous classes.
At the time being, there is only 1 post about anonymous classes in tests (thanks to Matthieu!). Compared to that, there are many PHP tool made just for mocking: Prophecy, Mockery, PHPUnit native mocks, Mockista and so on. If you're a developer who uses one of them, knows that he needs to add proper annotations to make autocomplete work, has the PHPStom plugin that fixes bugs in this autocomplete and it works well for you, just stop reading.This post is for developers who struggle with mocking and have a feeling, that they're doing something wrong.
He starts with an example of a test that creates a mock for an external request to the Heroku service using PHPUnit's mocking tools. He points out that this requires extra knowledge of the mocking methods and functionality to accomplish, potentially making it difficult to understand for those new to the tool. He then shares a refactor of the same test, this time making use of an anonymous class to mock out the needed findByCategoryId
method and return a response. He ends the post pointing out that, as a side effect of this refactoring (and other interface refactoring) you'll create more SOLID code and it can help make it easier to maintain in the future.