Testing with 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.
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.
final class ServiceTest extends TestCase
public function testFormat(): void
// Notice as the parameter is irrelevant.
String result = (new Service()).format(null);