Using Mockery as a mocking framework with PHPUnit

A few days ago I was explaining mocking to a few colleagues. I came up with the following quick n dirty code to show them the elegance of Mockery as a mocking framework.

The code is straight-forward: it checks the health of a server using a tiny heart beat script.

1. The script residing in the remote server:


2. The class that tries to fetch the status from the remote server:


3. The Http wrapper class that we will mock. Remember, in order to mock one object, we must be able to inject that object to the testing class using Dependency Injection.


4. Finally, the test suite. Observe that we have mocked the Http class here using Mockery and have set expected function call and an expected result as per our need.


5. Make sure you have the following libraries installed (they have great install instructions):

6. Run the unit test using phpunit and it should pass:

7. Btw, the actual functionality is pretty simple to use as well. Check this script:


This is a very very simple use case and just meant to give an introduction. If you’re serious about unit testing, you should dig deeper into the concepts as well as into the PHPUnit and Mockery library documentations.