问题
having this code
<?php
public function trueOrFalse($handler) {
 if (method_exists($handler, 'isTrueOrFalse')) {
  $result= $handler::isTrueOrFalse;
  return $result;
 } else {
  return FALSE;
 }
}
how would you unit-test it? is there a chance to mock a $handler? obviously i would need some kind of
<?php
$handlerMock= \Mockery::mock(MyClass::class);
$handlerMock->shouldReceive('method_exists')->andReturn(TRUE);
but it cannot be done
回答1:
Okay In your testCase class you need to use the same namespace of your MyClass class. The trick is to override built-in functions in your current namespace. So assuming your class looks like the following:
namespace My\Namespace;
class MyClass
{
    public function methodExists() {
        if (method_exists($this, 'someMethod')) {
            return true;
        } else {
            return false;
        }
    }
}
Here is how the testCase class should look like:
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);
    }
}
It works perfect for me. Hope this helps.
来源:https://stackoverflow.com/questions/37927273/how-to-unit-test-a-php-method-exists