【问题标题】:Stub PHP native methods存根 PHP 原生方法
【发布时间】:2011-02-02 22:39:15
【问题描述】:

在我的单元测试中,我希望对 php 的内置 file_get_contents() 方法的行为进行存根。

有没有办法在 PHP 中存根原生方法(例如 file_get_contents() 或 print_r())等?

【问题讨论】:

标签: php phpunit native mocking stub


【解决方案1】:

如果“存根”是指替换,则有一个 PHP override_function 函数;虽然它是 PECL 的一部分。你也可以rename他们。

【讨论】:

    【解决方案2】:

    runkit 是可能的。使用 runkit_function_copy 和 runkit_function_redefine 函数来复制和重新定义函数。您应该将 runkit.internal_override ini-setting 设置为 1 以修改内部函数。

    【讨论】:

      【解决方案3】:

      你不清楚“存根”是什么意思。

      你的意思是获取函数的文档,例如:

      /**
       * (PHP 5 &gt;= 5.1.0)<br/>
       * Sets the default timezone used by all date/time functions in a script
       * @link http://php.net/manual/en/function.date-default-timezone-set.php
       * @param timezone_identifier string <p>
       * The timezone identifier, like UTC or
       * Europe/Lisbon. The list of valid identifiers is
       * available in the .
       * </p>
       * @return bool This function returns false if the
       * timezone_identifier isn't valid, or true
       * otherwise.
       */
      function date_default_timezone_set ($timezone_identifier) {}
      

      ?

      【讨论】:

      【解决方案4】:

      由于PHP-5.3's namespace fallback policy,您可以在非全局命名空间上下文中覆盖对非限定函数名的调用:

      对于函数 […],如果命名空间函数 […] 不存在,PHP 将回退到全局函数 […]。

      即对非限定函数名称 file_get_contents() 的调用,例如可以通过提供 foo\file_get_contents() 来覆盖命名空间 foo


      我最近创建了库 PHP-Mock,它为一些非确定性 PHP 函数提供模拟,例如 time()

      【讨论】:

        猜你喜欢
        • 2023-03-15
        • 2015-07-18
        • 2017-04-27
        • 1970-01-01
        • 1970-01-01
        • 2010-10-03
        • 2016-09-21
        • 2012-06-11
        • 1970-01-01
        相关资源
        最近更新 更多