Testing with Test Doubles?

Dummy, Stub, Spy, Mock or Fake

Jesus Valera Reales
6 min readJun 11, 2020

--

Test Doubles

A Test Double is an object that can stand-in for a real object in a test, similar to how a stunt double stands in for an actor in a movie.

As I wrote in “The importance of the Tests in our Software”, there are several types of tests. They are also known as Test Doubles instead of “Mocks”.

The five types of Test Doubles are:

  • Dummy: It is used as a placeholder when an argument needs to be filled in.
  • Stub: It provides fake data to the SUT (System Under Test).
  • Spy: It records information about how the class is being used.
  • Mock: It defines an expectation of how it will be used. It will cause failure if the expectation isn’t met.
  • Fake: It is an actual implementation of the contract but is unsuitable for production.

The snippets are a pseudo-language based on a mix of PHP & Java.
The idea is to make it understandable to everyone familiar with OOP.

Dummy

The dummies are objects that our SUT depends on, but they are never used. We don’t care about them because they are irrelevant to the test scope.

Let’s imagine we have a service with a dependency that is irrelevant in the current test. We can perform something similar to the following snippet:

final class Service
{
public final String OUTPUT = 'something';

public function format(?Dependency dependency): String
{
// 'dependency' won't interfere in the expected result.
return self::OUTPUT;
}
}

final class ServiceTest extends TestCase
{
public function testFormat(): void
{
// Notice as the parameter is irrelevant.
String result = (new Service()).format(null);
self.assertSame(Service::OUTPUT, result);
}
}

--

--

Jesus Valera Reales

Competitive, entrepreneur and autodidact. Hard worker, lover of technology and free software.