有没有办法模拟/覆盖PHPUnit中的内置函数shell_exec。我知道Mockery,除了PHPUnit之外,我不能使用其他的库,.I已经尝试了超过3个小时,并且在某个地方卡住了。任何指针/链接都将非常感谢。我正在使用Zend-framework2
发布于 2016-09-27 01:41:50
有几个选项。例如,您可以在测试作用域的名称空间中重新声明php函数shell_exec。
请查看这篇很棒的博客文章:。
<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
//...
}
}现在,如果您在My\Namespace中的类中使用了全局shell_exec函数,那么它将使用您的自定义shell_exec函数。
您还可以将模拟函数放在另一个文件中(与SUT具有相同的名称空间),并将其包含在测试中。同样,如果测试具有不同的名称空间,您也可以模拟该函数。
发布于 2019-05-31 07:12:41
对非同构命名空间的回答;
正如@notnotundefined所指出的,这里的解决方案依赖于与被测试代码位于同一名称空间中的测试。下面是如何使用竞争的命名空间完成相同的测试。
<?php
namespace My\Namespace {
/**
* Override shell_exec() in the My\Namespace namespace when testing
*
* @return int
*/
function shell_exec()
{
return // return your mock or whatever value you want to use for testing
}
}
namespace My\Namespace\Tests {
class SomeClassTest extends \PHPUnit_Framework_TestCase
{
public function testSomething()
{
// The above override will be used when calling shell_exec
// from My\Namespace\SomeClass::something() because the
// current namespace is searched before the global.
// https://www.php.net/manual/en/language.namespaces.fallback.php
(new SomeClass())->something();
}
}
}发布于 2018-11-22 02:36:57
您可以尝试使用badoo/soft-mocks包模拟任何内置函数,包括像Mockery这样的自定义对象。例如
\Badoo\SoftMocks::redefineFunction('strlen', '', 'return 5;');这真的很有用,特别是对于依赖外部资源的内置函数。例如:
https://stackoverflow.com/questions/39706887
复制相似问题