...
/Bypassing External Dependencies with a Mocking Framework
Bypassing External Dependencies with a Mocking Framework
Learn what mock objects are, why they are important for testing, and how to use them.
We'll cover the following...
Introduction
Mock objects allow you to mimic/mock the behavior of real classes by guaranteeing determinate data output. This allows for easier testing since it isolates the code being tested and guards it against indeterminate data dependencies. A mocking framework is a library that easily creates and configures mock objects.
If mocking frameworks were not used, the process for creating mock objects would be more laborious. Mocking frameworks allow you to create these dependent classes without manually defining their implementation.
With mocks, you can set up an object’s method to return specific values based on specific inputs. You may also set various properties. You may even verify that the methods you set up are being called in the tested code. This ensures that the flow of the program happens as expected.
Mocking frameworks and preferred framework
Your unit test project may utilize numerous mocking frameworks. Some of these include the following::
- Moq
- NSubstitute
- Rhino Mocks
- FakeItEasy
- NMock3
Due to its widespread use, we’ll use the Moq framework and demonstrate its operation below.
Using the Moq framework
Let’s have a look at the application code and test it using mocks.
Example application code
The application code below is an API. You can think of an API as a software that constantly runs and listens to outside requests. When it receives a request, it performs CRUD (create, read, update, and delete) operations on entries in a database. APIs therefore contain no front-end code. Each time you use an application like WhatsApp, send an instant message or check the weather on your phone, you’re using an ...