phpphpunitprophecy

PHP Prophecy Stub method not called


I can't get this obvious test to pass. Foo gets a Bar in its constructor and when calling Foo::m(), Bar::bar() gets called.

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 fails to register the call to Bar::bar() somehow...

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

Solution

  • Your $bar variable contains an instance of ObjectProphecy, which is unrelated to the Bar class. Call $bar->reveal() to get a test double which is an extension of Bar:

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