Mocking in Unit Tests

Learn about mocks, their advantages, and how they can be used in unit testing.

Mocking in unit tests

Mocking is one of the fundamental pillars of unit tests. It allows us to provide our tests with fake dependencies instead of using the actual ones. Mocks can emulate how a service might behave. For example:

  • It can return expected/unexpected data to the caller.
  • It can raise a business logic or network-related error.

Thus, it’s easy to test the correct behavior of every single facet of our program. Before moving on, let’s go over some good principles that we should follow while writing unit tests:

  • We should test the expected behavior instead of the concrete implementation of the dependencies. In practice, we care about what the code does, not about how the code does the job.
  • Unit tests only have to test a single independent unit of our software.
  • We don’t have to rely on external dependencies in our tests as they’re unstable and potentially slow.

Let’s introduce an example to highlight the need for mocking in unit tests.

ACME e-commerce shop

The demo application will be an online shop. We will focus only on the function that allows users to buy stuff. Let’s see the skeleton of this function in a figure:

Get hands-on with 1200+ tech skills courses.