Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit: mocking the function

Tags:

php

tdd

phpunit

Is it possible to create a mock for the function?

UPD1:

$class->callback('callback_function');

I've tried to test whether callback_function was invoked once or not.

like image 550
zerkms Avatar asked Jul 15 '26 12:07

zerkms


1 Answers

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.

like image 170
Gordon Avatar answered Jul 21 '26 11:07

Gordon