Day11: Compare and contrast Mocking, Stubbing and Faking

Mock,stub and fake are all test doubles which are commonly used in automated unit testing. They look and behave like their product equivalents, but simplified. Using test doubles reduces complexity because it allows verifying code independently from the rest of the system. Sometimes, it's even necessary to execute the self-validating at all.

Although they are all test doubles, they're different implementation variations. 











Fakes: They are objects that have working implementations, but not the same as the production ones. Usually, they take some shortcut and have a simplified version of the production code.  

e.g.
The above picture shows a Fake AccountDAO that is an in-memory implementation of Data Access Object and will not engage database but just use a simple collection to store data. This allows testers to do integration test of services without starting up a whole database and performing time-consuming requests.

Stubs: They are objects that have predefined data and use it to answer the calls during tests when we can't or don't want to involve the reals objects that should answer the calls with real data.
e.g.
This example shows that a method calls an object to return some data from the real database. Instead of the real object, we introduce a stub within which just enough data has been defined to respond to the call during the test.

Mock: It's a method/object that simulates the behavior or a real method/object in controlled ways. we use mocks when we don't want to invoke the production code or there's no easy way to verify that the intended code was executed.
e.g.
In the above example, involving the real door and window is not easy or we don't want to do that each time when we test that if the security method is working. So we place door and window mocks in the test.
After execution of the securityOn method, window and door mocks recorded all interactions so that we can verify that window and door objects were instructed to close themselves. That's all we need to test from the SecurityCentral perspective.

0 comments:

Post a Comment