【问题标题】:how to unit-test a php method_exists()如何对 php method_exists() 进行单元测试
【发布时间】:2016-10-21 23:45:00
【问题描述】:

有这个代码

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

但是做不到

【问题讨论】:

  • 为什么你创建方法trueOrFalse你可以在代码中检查method_exists,因为如果方法存在isTrue并且总是返回true你可以简单地将它替换为单个method_exists()但是如果你方法isTrue返回的所有数据你可以简单的if(!method_exists) return false或几个数据,或者你可以创建抽象类并根据需要设置这个方法来进行parrenting。 p.s.对不起我的英语。
  • 这只是简化了。事实上isTrue 返回布尔值(假或真)作为其结果。所以问题是,是否有机会按原样测试它,还是需要重构?在这种情况下,是的,我可能需要从方法中删除 method_exists

标签: php unit-testing phpunit mockery


【解决方案1】:

好的,在您的 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);
    }

}

它非常适合我。希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2015-09-13
    • 2012-01-08
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 2013-09-30
    • 2019-01-05
    • 2011-03-16
    相关资源
    最近更新 更多