lstrojny/phpunit-function-mocker

允许通过使用命名空间来模拟其他无法测试的PHP函数。

1.1.0 2020-06-16 09:03 UTC

This package is auto-updated.

Last update: 2024-08-29 03:35:28 UTC


README

通过使用命名空间来模拟其他无法测试的PHP函数。

Build Status

<?php
namespace MyNamespace;

class Tool
{
    public function isString($string)
    {
        return strlen($string) > 0 && ctype_alpha($string);
    }
}
<?php

require_once 'PHPUnit/Extension/FunctionMocker.php';

class MyTestCase extends PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->php = PHPUnit_Extension_FunctionMocker::start($this, 'MyNamespace')
            ->mockFunction('strlen')
            ->mockFunction('ctype_alpha')
            ->getMock();
    }

    /** @runInSeparateProcess */
    public function testIsStringUsesStrlenAndCtypeAlpha()
    {
        $this->php
            ->expects($this->once())
            ->method('strlen')
            ->with('foo')
            ->will($this->returnValue(3))
        ;
        $this->php
            ->expects($this->once())
            ->method('ctype_alpha')
            ->with('foo')
            ->will($this->returnValue(false))
        ;

        $tool = new MyNamespace\Tool();
        $this->assertFalse($tool->isString('foo'));
    }
}

注意

使用@runInSeparateProcess注解确保模拟在PHP >=5.4中可靠工作。