how to unit-test a php method_exists()
Asked Answered
K

1

1

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

Ker answered 20/6, 2016 at 16:16 Comment(2)
Why you create method trueOrFalse you can check method_exists in code, because if method exist isTrue and always return true you can simple replace this to single method_exists() but if you method isTrue returned evrything data you can simple if(!method_exists) return false or several data, or you can create abstract class and set this method as require for parrenting. p.s. sorry for my English.Bitt
this is just simplified. in fact isTrue returns boolean (false or true) as its result. so question is, is there a chance to test it like it is, or refactoring is needed? in that case, yes i would probably need to get rid of that method_exists out of the methodKer
C
4

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.

Caboodle answered 20/6, 2016 at 17:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.