Mocking classes and objects is easy. But what about mocking the built in PHP functions like date or fopen? PHP-Mock is a library that (in most circumstances) lets you mock the responses of those functions. So, while previously if you had code that relied on date() you might start thinking of ways to wrap that usage in a mockable object, PHPMock allows you to control the response to be whatever you want.
While this might now be a big deal for a log of modern code, which tends on rely on abstraction into single-use classes, this is still a particularly handy thing to be able to do when you're dealing with legacy code. In that case, you probably don't want to immediately start moving things and wrapping method calls, but you still want to be able to test that things are doing what they ostensibly should be.
There's even a PHPUnit integration that allows you to write code like this:
use PHPMock; public function testOpenFile () { $file_path = "/path/to/file.jpg"; $fopen = $this->getFunctionMock(__NAMESPACE__, 'fopen'); $fopen->expects($this->once())->willReturnCallback(function($file, $mode) use ($file_path) { $this->assertEquals($file_path, $file); $this->assertEquals('r', $mode); return 'foo-stream'; }); $result = fopen($file_path); $this->assertEquals('foo-stream', $result); }
Things to keep in mind: The mocked method cannot exist in the global namespace. Also, you need to be clear about the namespace you assign the mock method to. If you declare the mock in namespace A, you can't use it in namespace B.