Skip to content

Test Double

Devrath edited this page Oct 25, 2023 · 4 revisions

github-header-image

What is a test double

A test double is a stunt double. It actually stands in the place of a real thing.

actors-stunt-doubles-fb110-png__700

What is the need for test double in unit testing

Scenario

  • We face many problems where a program is dependent on an external program or instance of an external program
  • Example your log-in screen can be dependent on any eternal service like google-login, facebook-login etc ..

Problem faced in scenario

  • We want to check scenarios like successful and failure in login and also need to check the login when the services are not available.
  • We can't ask the services to behave differently just so that we want to test the test cases. Since it is not our concern how the service works.

Solution for the Problem

  • Using the test doubles we can substitute the service with our own and change the behavior of it so that we can test our test cases.

Types of test double

screen_flow

When to use mocks and when to use fakes

When Mocks are used

  • They are used when there is no easy way to verify a specific piece of code is executed.
  • It is used when we need to test legacy code. Scenarios like when you don't have proper abstraction
  • Testing the code that you do not own like third-party code that you cannot access

When Fakes are Used

  • It is used to verify real-world production behavior in a simplified way.
  • One example is instead of using persistence storage, We use an in-memory list.

More observations

  • Sometimes when you use mock and write the test cases, the production code gets extended with new functionalities
  • The test cases might fail because the new functionalities are not mocked.
  • But using a fake you are forced to implement all the new implementations since the interface enforces that.
  • Overusing the mocks is always not good so just use it absolutely when necessary.
  • So if the code is legacy code and code that you do not own we can use the mocks else always go for fakes.