Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PhpUnit Mock an inbuilt function

Is there a way to mock/override an inbuilt function shell_exec in PHPUnit. I am aware of Mockery and I cannot use other libraries apart from PHPUnit.I have tried for more than 3hrs and somewhere stuck. Any pointers / links would be highly appreciated. I am using Zend-framework2

like image 800
notnotundefined Avatar asked Sep 26 '16 15:09

notnotundefined


1 Answers

There are several options. You could for example redeclare the php function shell_exec in the namespace of your test scope.

Check for reference this great blog post: PHP: “Mocking” built-in functions like time() in Unit Tests.

<php
namespace My\Namespace;

/**
 * Override shell_exec() in current namespace for testing
 *
 * @return int
 */
function shell_exec()
{
    return // return your mock or whatever value you want to use for testing
}
 
class SomeClassTest extends \PHPUnit_Framework_TestCase
{ 
    /*
     * Test cases
     */
    public function testSomething()
    {
        shell_exec(); // returns your custom value only in this namespace
        //...
    }
}

Now if you used the global shell_exec function inside a class in the My\Namespace it will use your custom shell_exec function instead.


You can also put the mocked function in another file (with the same namespace as the SUT) and include it in the test. Like that you can also mock the function if the test has a different namespace.

like image 63
Wilt Avatar answered Oct 23 '22 13:10

Wilt