Articles

Mocking Global Php 5.3 Functions Using Namespaces


Achieve 100% Code Coverage in PHP with a Mock of Global Functions

Let's say you'd like to achieve a 100% coverage of your code in your php application (you obsessive geek..). It's almost certain you'll need to start mock'ing things around. So far so good.. but sooner or later you will need to deal with the test cases for the code that use global php functions. How can you mock them? In this article I'll show you a small technique to allow you to mock global php functions. This will require your code to use namespaces, available since PHP 5.3.

Classical PHP Code example calling a global function

Suppose this is the code you'd like to test, a file called SomeClass.php:

It's fairly easy to have a unit test for the "success case" by just asserting the result value. What happens with the other use case, where the exception is thrown?
This is an extreme simple example, but what happens if something complicated has to be done when the call to socket_create fails for whatever reason? How can you be sure that the code is behaving like it should be?

The PHPUnit tests mocking a global function

This is our Test_SomeClass.php file:

Running phpunit will give you the 100% coverage :)

How about that 100% PHP Code Coverage?

With this little trick we can increase the testing level of the code. Most "normal" php code lacks good error handling (differences between cero, false, and null are among the #1's). Now everything can be tested at the highest levels possible, which is a novelty in the php language :) now go get that 100%!