Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

php - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 MyNamespace;

/**
 * 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 MyNamespace 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...