Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Mark Baker:
Extending final Classes and Methods by manipulating the AST
Nov 20, 2017 @ 16:38:32

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").

tagged: extend class method manipulate ast testing unittest final mockery tutorial

Link: https://markbakeruk.net/2017/11/19/extending-final-classes-and-methods-by-manipulating-the-ast/


Trending Topics: