Dave Hulbert's Today I Learned (TIL)


Notes on designing through mocking

date: 2014-10-30 21:44:07

My notes on Everzet's talk "Design how your objects talk through mocking" at PHPNW14

Different test doubles: Mocks, stubs, spies, dummies and fakes

Dummy

<?php
class Foo { public function __construct(Dummy $dummy) {} }
new Foo((new \Prophecy\Prophet)->prophesize(Dumnmy::class)->reveal());

Stub

<?php
function baz(Stub $stub) { return $stub->foo(123) === 'bar';}
$stub = (new \Prophecy\Prophet)->prophesize(Stub::class);
$stub->foo(123)->wilLReturn('bar');
baz($stub->reveal());

Mock

<?php
function foo(Mock $mock) { $mock->bar(123); }
$prophet = new \Prophecy\Prophet;
$mock = $prophet->prophesize(Mock::class);
$mock->bar(123)->shouldBeCalled();
foo($mock->reveal());
$prophet->checkPredictions();

Spy

<?php
function foo(Spy $spy) { $spy->bar(123); }
$spy = (new \Prophecy\Prophet)->prophesize(Spy::class);
foo($spy->reveal());
$spy->bar(123)->shouldHaveBeenCalled();

Fake

<?php
interface WebServiceInterface { public function strtoupper($data); }
class RealWebService implements WebServiceInterface {
    public function strtoupper($data) { return file_get_contents('api.com/strtoupper/'.$data); }
}
class FakeWebService implements WebServiceInterface {
    public function strtoupper($data) { return strtoupper($data); }
}

How mocking helps you follow SOLID principles

Testing outcomes vs testing communication between objects

Summary