kkreft
8/31/2017 - 9:48 AM

Source: https://stackoverflow.com/a/45975572

PHPUnit supports two ways of creating test doubles. Next to the legacy PHPUnit mocking framework it now supports prophecy out of the box.

PHPUnit Mocking Framework

The createMock method is used to create three mostly known test doubles. It's how you configure the object makes it a dummy, a stub, or a mock.

Dummy

Dummy is passed around, but never actually called, or if it's called it responds with a default answer (mostly null). It mainly exists to satisfy a list of arguments.

$dummy = $this->createMock(SomeClass::class);
// SUT - Subject Under Test
$sut->action($dummy);

Stub

Stubs are used with query like methods - methods that return things, but it's not important if they're actually called.

$stub = $this->createMock(SomeClass::class);
$stub->method('getSomething')
    ->willReturn('foo');

$sut->action($stub);

Mock

Mocks are used with command like methods - it's important that they're called, and we don't care much about their return value (command methods don't usually return any value).

$mock = $this->createMock(SomeClass::class);
$mock->expects($this->once())
    ->method('doSomething')
    ->with('bar');

$sut->action($mock);

Expectations will be verified automatically after your test method finished executing. In the example above, the test will fail if the method doSomething wasn't called on SomeClass, or it was called with arguments different to the ones you configured.

Spy

Not supported.

Prophecy

Prophecy is now supported by PHPUnit out of the box, so you can use it as an alternative to the legacy mocking framework. Again, it's the way you configure the object makes it becomes a specific type of a test double.

Dummy

$dummy = $this->prophesize(SomeClass::class);

$sut->action($dummy->reveal());

Stub

$stub = $this->prophesize(SomeClass::class);
$stub->getSomething()->willReturn('foo');

$sut->action($dummy->reveal());

Mock

$mock = $this->prophesize(SomeClass::class);
$mock->doSomething('bar')->shouldBeCalled();

$sut->action($dummy->reveal());

Spy

$spy = $this->prophesize(SomeClass::class);

// execute the action on subject under test
$sut->action($spy->reveal());

// verify expectations after 
$spy->doSomething('bar')->shouldHaveBeenCalled();