PHP 未调用预言存根方法

PHP Prophecy Stub method not called

我无法通过这个明显的测试。 Foo 在其构造函数中获取一个 Bar,当调用 Foo::m() 时,将调用 Bar::bar()。

use PHPUnit\Framework\TestCase;

class Bar {
    public function bar() {
        echo "BAR";
    }
}

class Foo {
    protected $bar;
    public function __construct($bar) {
        $this->bar= $bar;
    }
    public function m() {
        $this->bar->bar();
    }
}

class FooTest extends TestCase {

    public function testM() {
        $bar = $this->prophesize(Bar::class);
        $bar->bar()->shouldBeCalled();
        $foo = new Foo($bar);
        $foo->m();
    }
}

Prophecy 无法以某种方式注册对 Bar::bar() 的调用...

Some predictions failed:
  Double\Bar\P1:
    No calls have been made that match:
      Double\Bar\P1->bar()
    but expected at least one.

您的 $bar 变量包含一个 ObjectProphecy 实例,它与 Bar class 无关。调用 $bar->reveal() 得到一个测试替身,它是 Bar:

的扩展
public function testM()
{
    $bar = $this->prophesize(Bar::class);
    $bar->bar()->shouldBeCalled();
    $foo = new Foo($bar->reveal());
    $foo->m();
}