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:
/remote/heart.php
'online');
header("Content-type: application/json"); echo json_encode($response);
2. The class that tries to fetch the status from the remote server:
/test/Heartbeat.php
http = $http; }
public function checkHealth()
{
$url = 'http://localhost/remote/heart.php';
$response = $this->http->getResponse($url);
$beat = json\_decode($response);
return (!is\_null($beat) && $beat->status == 'online');
}
}
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.
/test/Http.php
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.
/test/HeartbeatTest.php
shouldReceive('getResponse')->andReturn('{"status":"online"}');
$heartbeat = new Heartbeat($http);
$response = $heartbeat->checkHealth();
$this->assertTrue($response);
}
}
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:
Emrans-MacBook-Air ~/Sites/test: phpunit HeartbeatTest.php
PHPUnit 3.6.10 by Sebastian Bergmann. .
Time: 0 seconds, Memory: 5.50Mb OK (1 test, 1 assertion)
7. Btw, the actual functionality is pretty simple to use as well. Check this script:
/test/check.php
checkHealth();
echo ($response) ? 'Online' : 'Offline';
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.