PhpUnit 模拟一个内置函数

2022-01-08 00:00:00 mocking php phpunit

有没有办法在 PHPUnit 中模拟/覆盖内置函数 shell_exec.我知道 Mockery 并且我不能使用除了 PHPUnit 之外的其他库.我已经尝试了超过 3 小时并且卡在了某个地方.任何指针/链接将不胜感激.我正在使用 Zend-framework2

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

推荐答案

有几个选项.例如,您可以在测试范围的命名空间中重新声明 php 函数 shell_exec.

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

查看这篇很棒的博客文章以获取参考:PHP:模拟"单元测试中的 time() 等内置函数.

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
        //...
    }
}

现在,如果您在 MyNamespace 的类中使用全局 shell_exec 函数,它将使用您的自定义 shell_exec 函数.

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

您还可以将模拟函数放在另一个文件中(与 SUT 具有相同的命名空间)并将其包含在测试中.像这样,如果测试具有不同的命名空间,您也可以模拟该函数.

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.

相关文章