Like unit-test php method_exists ()

with this code

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

how would you test it? is there a chance to mock $handler? obviously i need some

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

but it is impossible to do

+1
source share
1 answer

Good. In your testCase class, you need to use the same namespace of your class MyClass. The trick is to override the built-in functions in your current namespace. So, suppose your class looks like this:

namespace My\Namespace;

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

This is what the testCase class looks 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 great for me. Hope this helps.

+3
source

Source: https://habr.com/ru/post/1616952/


All Articles