Subscribe to PHP Freaks RSS

Mark Baker: Extending final Classes and Methods by manipulating the AST

syndicated from www.phpdeveloper.org on November 20, 2017

Mark Baker has an interesting post to his site where he shares a suggestion for making it easier to create unit tests for some of the more difficult parts of your unit tests. In the article he shows how to extend final classes and methods by manipulating the AST (abstract syntax tree structure) of the current code under test.

We know that we should always write unit tests for our code, and mock dependencies; but that isn’t always easy when we need to mock classes define as final, or that contain final methods. This isn’t normally a problem when we’re only working with classes within our own libraries and applications, because we control whether they are final or not, and we can type-hint these dependencies to interfaces. However, when the dependencies that we use are from external libraries, we lose that control; and it can become harder to test our own classes if we do need to mock final classes and they haven’t been built to interfaces.

He talks about how one tool, Mockery, allows some of this with its functionality but can still cause issues when mocks are passed instead of actual class instances. He then starts on a solution he has been trying to implement - a mocking library that makes use of the PHP_Parser package to make it possible to modify the structure of the code itself, not just put a wrapper (mock) around it. He includes a bit of code showing how to use that and the BetterReflection library to do some class introspection, locate files for testing and how to the tool to "de-finalize" a class (make it no longer "final").