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

PHPUnit fatal error call to undefined method on mock

我想测试是否调用了对象上的方法。我想通过模拟 Object 而不是任何特定的 class 来做到这一点。但是下面的代码会抛出一个致命错误:

class MyTest extends PHPUnit_Framework_TestCase
{
    public function testSomeMethodIsCalled()
    {
        $mock = $this->getMock('Object');
        $mock->expects($this->once())
                ->method('someMethod');
        $mock->someMethod();
    }
}

以上因错误而死:

Fatal error: Call to undefined method Mock_Object_204ac105::someMethod()

我确定有一种方法可以做到这一点,而不必编写实际上具有 someMethod() 方法的 class?

当您通过 $this->getMock() 创建 mock 时,您必须设置应该在 mock 中可用的方法数组,因此此代码应该有效:

$mock = $this->getMock('Object', ['someMethod']);