What is a test double and what are its types?

An application interacts with different components such as databases and third-party APIs. All such components are called dependencies of the system. When an application is tested, the aim is to see the correct functionality of the code without having to worry about external dependencies. That’s when test doubles come in handy. Test doubles are used in place of actual dependencies to test that the function or module is working properly. In this way, while performing integration tests, the person can focus on the actual code instead of the backend.

Types of test doubles

Different types of tests demand different functionalities from the test doubles. For instance, a test may or may not require the function to return some value. In this case, different types of doubles are required for different functionalities of the test.

There are three different types of test doubles:

  1. Fake
  2. Stub
  3. Mock

1. Fake

A fake provides a working implementation of an interface and does not deliver a canned (i.e. predetermined) response. It can or cannot be backed by a behavior.

Testing a database function with a fake double. The tested function is connected to a fake database, through the persistent layer, instead of the actual database.

2. Stub

A stub returns canned answers and does not provide a working implementation of the application interface. It is usually backed by a behavior.

Testing a function with stub double. Instead of using an actual database for testing the output of the function, a stub is used and its output is tested against the expected output.

3. Mock

A mock uses a fake module instead of a real one. It is a stateful process and needs the code to reload. Moreover, it does not return a value and thus is not suitable to check function behavior.

Testing a function with mock double. The connection is mocked by a 'fake' module instead of an actual one to test the activity of the function.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved