PHPUnit: mocking the function
Is it possible to create a mock for the function?
UPD1:
$class->callback('callback_function');
I've tried to test whether callback_function
was inv开发者_高级运维oked once or not.
Native functions cannot be mocked. You would need something like runkit or patchwork to do so.
What you could do though, is utilize a Strategy Pattern and wrap the native function calls into separate Command Objects or Closures/Lambdas and use those instead. Those can be passed around and exchanged freely.
Example 1 - Using a Lambda Function:
$callback = function() {
// a native function in here
}
$class->callback($callback);
Example 2 - Using a Command Object:
interface ICommand
{
public function execute();
}
class Callback implements ICommand
{
public function execute()
{
// a native function in here
}
}
$class->callback(array('Callback', 'execute'));
You can then mock those callbacks easily. I am not sure how PHPUnit implements the 'I have been called' thing. Either look into the sourcecode or add a subject/observer pattern.
If you have Runkit installed, this library can also work and gives you the same fluent interface as PHPUnit's mock framework:
https://github.com/tcz/phpunit-mockfunction
精彩评论