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

时间:2016-06-20 16:16:35

标签: php unit-testing phpunit mockery

拥有此代码

<?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);

但无法完成

1 个答案:

答案 0 :(得分:4)

好的在testCase类中,您需要使用MyClass类的相同名称空间。诀窍是覆盖当前命名空间中的内置函数。所以假设你的课程如下:

namespace My\Namespace;

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

以下是testCase类的外观:

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);
    }

}

它对我来说很完美。希望这会有所帮助。

相关问题