Test doubles also known as imposter has long been likened to the stunt doubles found in movies. They act in place of the movie actor/actress to perform stunts. In the world of software testing test doubles is a term that refers to objects used to replace objects in production. This article answers questions such as:
- Why we need a test double?
- The different types of test doubles.
- What look out for when using a test double.
Why use a test double
We use test doubles in any of these situations
- The object it depends on is not available.
- There is an uncertainty in the result the object will return.
- Running the object will lead to undesirable side effects.
Types of test doubles
We look at five(5) types of test doubles.
Dummy Object: As the name implies are dummies, nothing special about them. They are in use when you need to fill a position, as a necessary parameter to call a method or create an instance of a class. Dummy objects are empty, no methods, no properties, so it cannot take any action and does not need to.
Fake Object: Like an imitation of an original look like the original but is lacking in some ways. The fake object unlike the dummy object contains some implementation of the object in production. Unlike the object in production, fake objects have a lot of short cuts and are more simplified. The shortcut and simplification allow for the avoidance of undesirable side effects. An in-memory database used in testing is an example of a fake object.
Test Spy: Test spy like a spy sits back to gather information about the interaction of the logic under test and the object it is replacing. The details in this information are verified after the logic under test is done with the test. Spies verifies actions felt outside the code under test.
Mock: A Mock is like a spy, but an impatient one if I may say. A mock verifies the action triggered by the logic under test, but felt by other systems takes place by defining the expectations for it before the logic under test is run.
Test stub: A test stub is an object that has no logic but only a predefined response.
What to avoid when using test doubles
These are a few tips to have in mind when using test doubles.
- Do not use too many test doubles in a test.
- Your test doubles should not be complex.
- Do not replace data structures with test doubles.
In conclusion, I hope this explains to beginners what test doubles are and the various types. If you have made it here kindly like the article and drop a comment. Thanks.