Before understanding test doubles, lets try to understand the core of unit testing and its principles.
Unit testing means testing out a very small piece of code that can be logically isolated from the entire software. Most common use cases of unit testing include testing of methods or sub-routines. It is very important to not that the isolated piece of code should not interact with any other component. In that case it becomes an interaction test.
What do you do when your method interacts with a 3rd party service or queries the database?
Enter Test Doubles
This term originates from stunt doubles. Test doubles can be used as replacements for testing out internal components. This helps us isolates interactions from within the piece of code under test
Dummies are placeholders objects or variables that are sent to the test, merely to fulfil the signature requirements. They can be functions with no implementation or null values. They are not utilized in the test and hence have no bearing on the outcome of the unit test.
Fakes are a type of test doubles that have a real implementation. But the implementation is not a full fledged one but rather a shortcut 1. For eg. If you have a database interaction, you can create an in-memory database. This way the unit test becomes isolated from the database interaction and it would also help in faster execution.
Stubs are a form of test doubles where the implementation is hard-coded. A stub cannot respond beyond what is hard-coded within its logic.
Spies are used to simulate output behavior. For e.g. when you want to test out an email, you don’t want to send actual emails every time. In this case you can use a spy to detect the number of times the email method is called.
Conclusion – Test Doubles
Test doubles can be really tricky and confusing. So instead of focusing on the definitions, we recommend that you focus on the meaning and the use cases around them. We will be adding specific use cases for each test double type.