对模拟上未定义方法的错误调用 PHPUnit


PHPUnit error call to undefined method on mock

当我在简单类模拟上调用 mymethod() 时,我收到错误:调用未定义的方法 Mock_SimpleInterface_8a93e777::mymethod()。

class PlaygroundTest extends 'PHPUnit_Framework_TestCase 
{
    public function testMock()
    {
        $class     = $this->getMockBuilder(''Playground'Simple')->getMock();
        $class->mymethod();
    }
}

简单类实现

namespace Playground;
class Simple
{
    public function mymethod()
    {
        print "Hey!";
    }
}

根据 PHPUnit 文档 (https://phpunit.de/manual/5.1/en/test-doubles.html),它指出"默认情况下,原始类的所有方法都替换为仅返回 null(不调用原始方法)的虚拟实现。

我不应该能够调用 mymethod() 并获取空返回值吗?我想避免指定所有类方法。PHPUnit 应该足够聪明,知道哪些方法可以在模拟上调用或不调用。

这是一个错误吗?我正在使用 PHPUnit 5.1.4

您的假设是正确的,因此您在其他地方有错误或没有显示真正的代码。

模拟类名Mock_SimpleInterface_8a93e777表明你实际上并没有模拟'Playground'Simple而是'Playground'SimpleInterface,这可能不包含mymethod()