【问题标题】:Is it possible to mock the non-existence of a function in PHPUnit?是否可以模拟 PHPUnit 中不存在的函数?
【发布时间】:2015-11-07 12:44:31
【问题描述】:

我有一个单元测试来检查如果未安装 openssl_random_pseudo_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();
}

【问题讨论】:

    标签: php mocking phpunit


    【解决方案1】:

    不直接,但您可以使用Can I "Mock" time in PHPUnit? 中所述的小技巧来模拟function_exists

    先决条件

    • 被测类 (CUT) 位于 PHP 命名空间中
    • function_exists() 以其非限定名称调用(即 not\function_exists()

    示例

    假设,CUT 如下所示:

    namespace Stack;
    class Salt
    {
        ...
            if (function_exists('openssl_random_pseudo_bytes'))
        ...
    }
    

    那么这是你的测试,在同一个命名空间中:

    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_random_pseudo_bytes”除外。

    如果您的测试位于不同的命名空间中,您可以像这样为每个文件定义多个命名空间:

    namespace Stack
    {
        function function_exists($function)
        ...
    }
    namespace StackTest
    {
        class SaltTest extends \PHPUnit_Framework_Test_Case
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-13
      • 1970-01-01
      • 2015-03-23
      • 1970-01-01
      • 1970-01-01
      • 2017-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多