Understanding Mocking

Learn about mock and its uses in a test in this lesson.

What is a mock?

A mock is a type of test double. A test double is a replacement for part of a codebase to make testing easier. For instance, web API calls are often mocked. This is useful for a few reasons:

  • To ensure the web API call response is consistent. The data behind the real web API will probably change over time, causing the real web API response to vary.

  • To speed up the test. Web API requests are slow.

  • To reduce costs if the web API is a third-party paid service.

Mock vs. stub

Another type of test double is a stub. Stubs are prewritten alternative implementations for part of the code. In the example below, FakeApi is a stub that we have fully implemented:

 ...