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
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
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
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
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.
Im pretty pleased to find this great site. I need to to thank you for ones time for this particularly fantastic read!! I definitely loved every little bit of it and I have you saved as a favorite to see new stuff on your blog.
Simply want to say your article is as amazing. The clarity in your post is
just excellent and i could assume you’re an expert
on this subject. Fine with your permission let me to grab your feed to keep updated with forthcoming post.
Thanks a million and please continue the rewarding
work.
Way cool! Some extremely valid points! I appreciate you penning this
article plus the rest of the site is also really
good.