2016-09-26 73 views
0

有没有办法模拟/覆盖内置功能shell_execPHPUnit。我知道Mockery,我不能使用除PHPUnit之外的其他库。我尝试了3个多小时,并在某处卡住了。任何指针/链接将不胜感激。 我正在使用Zend-framework2PhpUnit模拟内置功能

回答

4

有几种选择。例如,您可以在测试作用域的名称空间中重新声明php函数shell_exec

检查参考这个伟大的博客文章: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 
     //... 
    } 
} 

现在,如果你使用的全局shell_execMy\Namespace类内部功能将使用您的自定义shell_exec函数。

+0

只有当您的测试脚本和实际脚本位于相同的命名空间时,您的方法才有效。我的命名空间位于单独的命名空间中。 – Thabung

+0

为此,您的测试的名称空间应与SUT(被测系统)的名称空间相匹配。这是一种常见的方法。另请参阅[此问题](http://stackoverflow.com/q/8313283/1697459)或[此问题](http://stackoverflow.com/q/12117254/1697459)以供参考。 – Wilt

+0

不错的方法;) – hassan