如何对 php method_exists() 进行单元测试

how to unit-test a php method_exists()

有这个代码

<?php
public function trueOrFalse($handler) {
 if (method_exists($handler, 'isTrueOrFalse')) {
  $result= $handler::isTrueOrFalse;
  return $result;
 } else {
  return FALSE;
 }
}

您将如何对其进行单元测试?有机会模拟 $handler 吗?显然我需要某种

<?php
$handlerMock= \Mockery::mock(MyClass::class);
$handlerMock->shouldReceive('method_exists')->andReturn(TRUE);

但做不到

好的,在您的测试用例 class 中,您需要使用与 MyClass class 相同的名称空间。诀窍是覆盖当前命名空间中的内置函数。因此,假设您的 class 如下所示:

namespace My\Namespace;

class MyClass
{
    public function methodExists() {
        if (method_exists($this, 'someMethod')) {
            return true;
        } else {
            return false;
        }
    }
}

测试用例 class 应该是这样的:

namespace My\Namespace;//same namespace of the original class being tested
use \Mockery;

// Override method_exists() in current namespace for testing
function method_exists()
{
    return ExampleTest::$functions->method_exists();
}

class ExampleTest extends \PHPUnit_Framework_TestCase
{
    public static $functions;

    public function setUp()
    {
        self::$functions = Mockery::mock();
    }
    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        self::$functions->shouldReceive('method_exists')->once()->andReturn(false);

        $myClass = new MyClass;
        $this->assertEquals($myClass->methodExists(), false);
    }

}

它非常适合我。希望这有帮助。