如何对php method_exists()进行单元测试 [英] how to unit-test a php method_exists()

查看:101
本文介绍了如何对php method_exists()进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有此代码

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

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

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

但无法完成

推荐答案

好的,在您的testCase类中,您需要使用与MyClass类相同的名称空间.技巧是覆盖当前名称空间中的内置函数.因此,假设您的课程如下所示:

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

这是testCase类的外观:

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.

这篇关于如何对php method_exists()进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆