Subscribe to PHP Freaks RSS

Larry Garfield: Don't use Mocking libraries

syndicated from www.phpdeveloper.org on September 21, 2018

Larry Garfield has written up a post with a somewhat controversial headline, especially for anyone that's done any kind of unit testing on a larger codebase. His suggestion is to no use mocking libraries and some other techniques that can replace them.

I am all for testing. [...] There's a lot of opinions on what constitutes a "good" test, of course, and much is subjective to the type of code you're working on. However, since the release of PHP 7 I've found that while writing tests... I am never using a mocking library. In fact, I'm going to go as far and say that you should never use a mocking library in PHP 7.

Before all of you gasp, clutch your pearls, and send ninja hit squads after me, let me justify that position.

He starts off by defining what a "mock" is a more general sense and then, more specifically, how mocking libraries are mostly implemented in PHP. He covers the DSL (domain specific language) knowledge that's required to use most of them and how something already included in PHP 7 - anonymous classes - could be a viable alternative. He goes on to show examples of using this method rather than a mock for simple object handling and even recommends making an actual class (just for testing) if the need is there. He ends the post talking about the "upper bounds" of when this might not be as useful and how this can actually be good (using it as an indicator that you need to refactor the main code to simplify).