PHP Unit Test Doubles

Mocking in Unit Testing is an important concept when you get move to the more behavior driven testing. Lets go over this quickly to get you started.

Test Doubles

A test double is used to test a unit without having to rely on other injected objects which might not be available for testing or might return unreliable results. A test double will fill that objects place and we can then define this mock as if it was this real object. We are essentialy imitating other real objects.

With the createMock function you can create one of the 3 types of test doubles.

Dummy

A dummy is a test double that is passed around but never called. Or if its called it will always respond with null. You use this if you just want to pass some things around.

$dummy = $this->createMock(DummyClass::class);

$someClass->someMethod($dummy);

Stub

A stub is a test double that is passed around and also called. A method can be called on it and you can define what these should return. But it does not matter if this stubs methods or called or not.

$stub = $this->createMock(Stubclass::class)
            ->method('someStubMethod')
            ->willReturn('foo');
            
$someClass->someMethod($stub);

Mock

A mock is a test double that verifies expectations. You can expect it to be called x amount of times. There will be an assertion on this. If this mock is not called the amount of times as was expected then your test will fail.

$mock = $this->createMock(Mockclass::class)
            ->expects($this->once())
            ->method('someMockMethod')
            ->willReturn('foo');

$someClass->someMethod($mock);

So when we actually use this?

To mock repositories because we don’t want to test with the actual persistence. This will result in side effects and unnecessary slow downs. When we are testing our services we don’t want to test our repositories we mock these repositories by imitating and telling it what behavior we expect.