Introduction to Mocking

Get familiar with the concept of mocking in the context of unit testing.

In automated testing, mocking refers to creating fake or simulated objects and behaviors to isolate and test a software application’s specific components or functionalities. Mocking is commonly used in unit testing to ensure that individual units of code—including functions, methods, and classes—behave as expected, even if they rely on external dependencies, such as databases, APIs, or services.

For example, we may have a dependency in a class we test that normally calls an external service via the network. This cannot be executed in unit testing because we don’t test connections with external services. Therefore, instead of using a real implementation of the dependency that makes the network call, we would create a fake implementation that pretends to make a call and returns the expected results.

Here’s how we typically achieve mocking:

  1. An abstraction (an interface or an abstract class) is inserted as a dependency into the class under test.

  2. The test creates a dynamic implementation of this abstract object and sets its public methods and/or properties to return some fixed values.

  3. The mocked object is injected into the class under test to assess the remaining logic.

Using mocking in xUnit

The following playground demonstrates how mocking works:

Get hands-on with 1200+ tech skills courses.