如何模拟名称为 "method" 的方法?

How to mock up a method whose name is "method"?

class Foo {
  public function method() {

  }
  public function bar() {

  }
}

如果我有 class Foo,我可以使用以下语法更改 bar 的行为。

$stub = $this->createMock(Foo::class);

$stub->expects($this->any())
    ->method('bar')
    ->willReturn('baz');

Limitation: Methods named "method" The example shown above only works when the original class does not declare a method named "method". If the original class does declare a method named "method" then $stub->expects($this->any())->method('doSomething')->willReturn('foo'); has to be used.

https://phpunit.de/manual/current/en/test-doubles.html#test-doubles.stubs


但我的问题是,如何更改 Foo::method() 在 PHPUnit 中的行为?可能吗?

这很好用: 使用 PHP 7.0.9/PHPUnit 4.8.27

测试
public function testMethod()
{
    $stub = $this->getMock(Foo::class);

    $stub->expects($this->once())
        ->method('method')
        ->willReturn('works!');

    $this->assertEquals('works!', $stub->method('method'));
}

编辑:

使用 PHP 7.0.9/PHPUnit 5.6.2 进行测试另外:

public function testMethodWithDeprecatedGetMock()
{
    $stub = $this->getMock(Foo::class);

    $stub->expects($this->once())
        ->method('method')
        ->willReturn('works!');

    $this->assertEquals('works!', $stub->method('method'));
}

public function testMethodWithCreateMock()
{
    $stub = $this->createMock(Foo::class);

    $stub->expects($this->once())
        ->method('method')
        ->willReturn('works!');

    $this->assertEquals('works!', $stub->method('method'));
}

只显示第一种方法的弃用警告,但测试成功。