可以模拟PHPUnit中函数的不存在吗?
我有一个单元测试,检查在未安装可以模拟PHPUnit中函数的不存在吗?,php,mocking,phpunit,Php,Mocking,Phpunit,我有一个单元测试,检查在未安装openssl\u random\u pseudo\u bytes时是否引发异常。但是,如果已安装,则当前将跳过它。不过,这对我来说并不令人满意,因为它会导致不完美的测试运行。我可以设置单元测试通过,但这感觉像是作弊 有人有什么想法吗 这是我目前的测试: public function testGenerateOpenSSLThrowsExceptionWhenFunctionDoesNotExist() { if (function_exists('ope
openssl\u random\u pseudo\u bytes
时是否引发异常。但是,如果已安装,则当前将跳过它。不过,这对我来说并不令人满意,因为它会导致不完美的测试运行。我可以设置单元测试通过,但这感觉像是作弊
有人有什么想法吗
这是我目前的测试:
public function testGenerateOpenSSLThrowsExceptionWhenFunctionDoesNotExist()
{
if (function_exists('openssl_random_pseudo_bytes')) {
$this->markTestSkipped('Cannot run test: openssl_random_pseudo_bytes function exists.');
}
$this->_salt->generateFromOpenSSL();
}
不直接,但您可以使用中所述的小技巧模拟
函数\u的存在
先决条件
- 被测试的类(CUT)位于PHP命名空间中
function\u exists()
以其非限定名称调用(即不是\function\u exists()
)
例子
比如说,伤口看起来像这样:
namespace Stack;
class Salt
{
...
if (function_exists('openssl_random_pseudo_bytes'))
...
}
namespace Stack
{
function function_exists($function)
...
}
namespace StackTest
{
class SaltTest extends \PHPUnit_Framework_Test_Case
...
}
这是您的测试,在同一命名空间中:
namespace Stack;
function function_exists($function)
{
if ($function === 'openssl_random_pseudo_bytes') {
return SaltTest::$opensslExists;
}
return \function_exists($function);
}
class SaltTest extends \PHPUnit_Framework_Test_Case
{
public static $opensslExists = true;
protected function setUp()
{
self::$opensslExists = true;
}
public function testGenerateOpenSSLThrowsExceptionWhenFunctionDoesNotExist()
{
self::$opensslExists = false;
$this->_salt->generateFromOpenSSL();
}
}
命名空间函数将优先于核心函数,并将所有参数委托给它,但“openssl\u random\u pseudo\u bytes”除外
如果您的测试位于不同的命名空间中,则可以按如下方式为每个文件定义多个命名空间:
namespace Stack;
class Salt
{
...
if (function_exists('openssl_random_pseudo_bytes'))
...
}
namespace Stack
{
function function_exists($function)
...
}
namespace StackTest
{
class SaltTest extends \PHPUnit_Framework_Test_Case
...
}