Test Stubs, Mocks and Spies

Test Stubs, Mocks and Spies
Photo by Dmitry Ratushny / Unsplash

In software testing, a test stub is a small piece of code that stands in for a larger component or system in order to test the behaviour of the code that interacts with it. Test stubs are often used to isolate the unit under test and verify that it behaves as expected.

A test mock is a fake implementation of a component or system that is used in place of the real implementation in order to test the behaviour of the code that interacts with it. Test mocks are often used to verify that the code under test is calling the correct functions with the correct arguments, and handling the returned values correctly.

A test spy is a function that records arguments, return value, the value of this, and exception thrown (if any) for all of its calls. Test spies are often used to verify that a function was called a certain number of times, or that it was called with the correct arguments.

Test stubs, mocks, and spies are all types of test doubles, which are used to isolate the unit under test and verify its behaviour in a controlled environment. They are commonly used in unit testing to ensure that the code under test is working correctly and that the test results are reliable and consistent.