Like many stories these days, this story started with a tweet from Stefan Koopmanschap.

In short: you can’t mock classes defined as final with PHPUnit.

But how can you test a class properly that depends on such a final class, if you can’t mock it?

The solution is simple but it requires you to write a mocking class that uses reflection to override the blockade introduced by the final visibility.

https://gist.github.com/DragonBe/24761f350984c35b73966809dd439135

This doesn’t solve the issue that you cannot mock final classes in PHPUnit, but it does give you a non-intrusive solution to test without having a dependency on other classes.


Michelangelo van Dam

Michelangelo van Dam is a senior PHP architect, PHP community leader and international conference speaker with many contributions to PHP projects and community events.

2 Comments

Stephan Hochdörfer · 25/07/2017 at 09:00

As an alternative you could provide your own filestream stream wrapper implementation and load it during the test run. The custom implementation would simply strip the “final” keyword from all loaded classes. Problem solved, the magic way 😛

    Michelangelo van Dam · 25/07/2017 at 09:05

    And I expect you have a working example to show this solution?

Comments are closed.