tcz/phpunit-mockfunction

该软件包的最新版本(v1.0.0)没有提供许可证信息。

使用 runkit 模拟 PHP 函数(包括用户定义和系统函数)的 PHPUnit 扩展

v1.0.0 2014-03-20 18:50 UTC

This package is not auto-updated.

Last update: 2024-09-24 06:01:14 UTC


README

MockFunction 是一个 PHPUnit 扩展,使用 runkit 模拟 PHP 函数(包括用户定义和系统函数)或静态方法,并使用 mockobject-style 调用匹配器、参数约束以及所有这些魔法。

要使用此扩展,您必须首先安装 runkit(PECL 软件包)。有关工作版本,请参阅 https://github.com/zenovich/runkit/

要模拟系统函数(而非用户定义的函数),您需要在 PHP 配置中启用 runkit.internal_override

安装

如果您使用 composer,安装 MockFunction 非常简单

"require-dev": {
    "tcz/phpunit-mockfunction": "1.0.0"
}

然后

php composer.phar update tcz/phpunit-mockfunction

使用方法

假设您在一个 PHPUnit 测试中

// Back to the future:
$flux_capacitor = new PHPUnit_Extensions_MockFunction( 'time', $this->object );
$einsteins_clock = time() + 60;
$flux_capacitor->expects( $this->atLeastOnce() )->will( $this->returnValue( $einsteins_clock ) );

其中 $flux_capacitor 是存根函数。它可以设置与 MockObject 相同的流畅接口(当然不包括方法)。

构造函数的第二个参数($this->object)是我们期望函数被调用的对象。从这里开始,“模拟”才会生效,从所有其他来源它将执行“正常”函数(见下一行)。

变量 $einsteins_clock 包含我们将返回的值,而不是“常规”值(我们为当前时间添加 1 分钟)。

在下一行中,我们使用模拟对象的流畅接口设置模拟函数。

模拟函数对测试对象实例有效,直到调用 $flux_capacitor->restore();。如果在测试用例的最后忘记这样做,通常不会成问题,因为您将使用每个测试用例重新测试您的测试类的新实例。

要模拟静态方法,您可以使用 PHPUnit_Extensions_MockStaticMethod 类。它的工作方式与函数相同。

$mocked_static = new PHPUnit_Extensions_MockStaticMethod( 'MyClass::myMethod', $this->object );

高级模拟

您可以使用所有调用匹配器、约束和存根返回值,例如

// This will execute the original function at the end, but will test 
// the number of exections ( $this->once() ) and the correct parameter ( $this->equalTo() ).
$mocked_strrev = new PHPUnit_Extensions_MockFunction( 'strrev', $this->object );
$mocked_strrev->expects( $this->once() )->with( $this->equalTo( 'abc' ) )->will( $this->returnCallback( 'strrev' ) );


// This object cannot execute shell_exec.
$mocked_shell = new PHPUnit_Extensions_MockFunction( 'shell_exec', $this->object );
$mocked_shell->expects( $this->never() );


// Expecting to check the existence of 2 file, returning true for both.
$mocked_file_exists = new PHPUnit_Extensions_MockFunction( 'file_exists', $this->object );
$mocked_file_exists->expects( $this->exactly( 2 ) )
    ->with(
        $this->logicalOr(
            $this->equalTo( '/tmp/file1.exe' ),
            $this->equalTo( '/tmp/file2.exe' )
        )
    )->will( $this->returnValue( true ) );

有关更多信息,请参阅 http://www.phpunit.de/manual/3.0/en/mock-objects.html

Bitdeli Badge Build Status