DEV Community

Ainama Sylvain💙
Ainama Sylvain💙

Posted on • Updated on

PHPUNIT:Demystifying the double test (Dummy,Stub,Mock)


This article will help you differentiate between a Dummy, a Stub and a Mock.

Test Double

In unit testing often, we often get to test classes.
Classes without dependencies are easy to test, but with dependencies it becomes much more complicated.
We can test a class with all its dependencies but it can be very complicated. The best solution is to isolate it from all its dependencies.
This is when the liners come in.
Take for example an actor often during filming the actor needs an understudy to perform stunts that one asks of him, it is exactly the same principle for the doublings in programming.

Alt Text
The problem with liners is that you usually don't know how to identify them.
Do we use a mock, a stub or a dummy.

But what is the difference?

To explain the difference between a mock, a stub or a dummy, we will first see their definitions.

What is a Dummy?

A dummy is an empty class that we can use when we need to instantiate an object dependent on it.
It aims to make believe that a class exists to the one that we want to test.
It is usually passed as a parameter but never called.
If called, its functions will always return null.

  $client = $this->getMock('GuzzleHttp\Client');
Enter fullscreen mode Exit fullscreen mode

What is a Stub?

A Stub is a dummy that will be customizable.
It will correspond to what we expect.
He can redefine his methods and tell him what to return.

  $stub = $this->createMock(Stubclass::class)

Enter fullscreen mode Exit fullscreen mode

What is a Mock?

A mock is a duplicate that checks expectations.
We can make it check that the method is called x times like never.
If the simulation is not done as many times as expected the test will fail.
Unlike the Stub a Mock can throw exceptions if it does not receive the correct calls.
The purpose of the mock is not to be interested in the return value but rather to be interested in the method which is called and to know how many times and with what arguments.

The execution will be launched once

  $mock = $this->createMock(Mockclass::class)
      // Once() one time

Enter fullscreen mode Exit fullscreen mode

The execution will never be launched

  $mock = $this->createMock(Mockclass::class)

Enter fullscreen mode Exit fullscreen mode


Now you will no longer confuse Mock, Stub and Dummy.
Now you will see more clearly !!

Alt Text

Top comments (0)