Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 断言函数被调用_Php_Phpunit - Fatal编程技术网

Php 断言函数被调用

Php 断言函数被调用,php,phpunit,Php,Phpunit,使用phpunit进行测试时,我想断言一个函数调用: 给定一个类: Class TimeWrapper { public function time() { return time(); } } 及其单元测试: Class TimeWrapperTest extends PHPUnit_FrameworkTestCase { public function testTime() { //Pseudocode as example of a possible solu

使用phpunit进行测试时,我想断言一个函数调用:

给定一个类:

Class TimeWrapper {
  public function time() {
    return time();
  }
}
及其单元测试:

Class TimeWrapperTest extends PHPUnit_FrameworkTestCase {
  public function testTime() {
    //Pseudocode as example of a possible solution:
    $this->assertCallsFunction("time");
  }
}
我特别寻找一种测试全局函数调用的方法


FWIW:对于rspec,我使用。我希望在PHPUnit中实现类似或完全类似的目标。

不确定是否已经为此做了一些事情


但是如果您试图自己实现它,您可以查看一下

如果目标是验证
TimeWrapper
调用内置PHP函数
time
,那么您需要使用扩展。这将允许您将内置函数替换为记录调用的您自己的版本。您需要在
php.ini
中启用
runkit.internal\u override
设置,以便重命名内部函数

class TimeWrapperTest extends PHPUnit_Framework_TestCase {
    static $calledTime;

    function setUp() {
        self::$calledTime = false;
    }

    function testTimeGetsCalled() {
        $fixture = new TimeWrapper;
        try {
            runkit_function_rename('time', 'old_time');
            runkit_function_rename('new_time', 'time');
            $time = $fixture->time();
            self::assertTrue('Called time()', $calledTime);
        }
        catch (Exception $e) {
            // PHP lacks finally, but must make sure to revert time() for other test
        }
        runkit_function_rename('time', 'new_time');
        runkit_function_rename('old_time', 'time');
        if ($e) throw $e;
    }
}

function new_time() {
    TimeWrapperTest::$calledTime = true;
    return old_time();
}
如果您不能使用扩展或者只是想避免这种欺骗,那么可以修改
TimeWrapper
,以允许您重写在运行时调用的函数

class TimeWrapper {
    private $function;

    public function __construct($function = 'time') {
        $this->function = $function;
    }

    public function time() {
        return call_user_func($this->function);
    }
}

使用上面的测试用例,不调用
runkit\u函数\u rename
并将
new\u time
传递给
TimeWrapper
构造函数。这里的缺点是,每次调用
TimeWrapper::time

时,您将在生产中支付(可能很小的)性能损失。您阅读了吗?是的。但是,他们不允许您存根全局函数或内置函数。SUT是一个Drupal插件。Drupal是一种CMS,它的所有API都在全局空间中:例如,cache_get()my DrupalWrapper调用该函数,我对包括Drupal,也不对测试其整个堆栈感兴趣。因此,我想要存根“cache_get()”