Mocking for unit tests — Understand the concept

Dipak Gawade
5 min readDec 15, 2019

Unit testing is testing the behavior of single unit (e.g. class). It helps to detect class level issues early. It also serves as first level of regression when other developers are modifying the code.

The simplest example can be implementing the Add() method in calculator and testing the output for different inputs.

Add feature in Calculator

If we write few simple unit tests for this function, those can be

Few unit tests for Add feature

If you check the last test, addition of Int.MaxValue and Int.MaxValue, makes us think what can be the output. We need to decide the behavior for such cases, handle them and pass the tests.

Such simple features can be tested without mocking. However, product development in object oriented environment is not single-class deal. The class you need to test might be coupled with other classes e.g. Account class depends on InterestCalculator class, EmployeesManager class holds the reference of EmployeeData etc. In such cases, writing unit tests can be bit tricky.

Consider, you are testing the business layer class which holds the reference of data layer class which is responsible for fetching data from database, for every new test in business layer, you need to reach data layer for data and data layer will reach database for the same. So for 5 tests, you need to make 5 different entries in database. This has overhead in terms of — time as data fetching operation will take time resulting in time consuming unit tests and memory as we need to store dummy data in database.

This can be saved through mocking. Mocking is ‘mimicking’ the behavior of existing class/interface and controlling the result. This is to avoid execution of real coupled class as that would be expensive.

What does this mean? Consider ‘mock’ fire drill. The scenario to test here is, there will be fire and people need to evacuate the building as early as possible. However, if they want to test the ‘evacuation’ operation, putting fire in company would be risky and expensive. So what do they do? They ‘assume’ the fire is there, and test evacuation process accordingly. This is mocking.

So if class A depends on class B, and we need to test only class A, we would create mock of class B and use so that we would avoid execution of real class B.

What are different mock frameworks?

  1. Nmock
  2. Moq
  3. nSubstitute
  4. TypeMock etc.

The selection of mocking framework should be based on-

  1. Learning curve — easy to use
  2. Maintainability — readable
  3. Capability — variety of features e.g. sequence control, event testing.

Some mocking frameworks let you mock classes with virtual functions, some let you mock only interfaces. Some mocking frameworks let you control the execution for repeated calls to same method, some do not.

Having said that, the main purpose of this article is to understand what these frameworks really do behind the curtains? Can we achieve the same without using mocking framework? Yes. How?

Consider the problem statement — We have SportsResult class which provides sports percentile marks for student

The above class is then used by main Result application to determine the final result(pass/fail). That is bit tricky logic as there are some combinations decided by school.

We need to test the GetResult method as there are chances we may miss some cases in development.

There are some more cases but we have started with the above four. Now to write tests using mocking concepts, but without mocking framework, we would write as-

First create dummy implementation of IResult interface, and then just return that value that first test demands

Return hard-coded to 50 as first test demands

Pass the instance of this dummy class to test class and test the output

Use the dummy class instance to test the output

Similarly, you need to introduce more mock classes of same interface and pass them to test the outputs.

So we can achieve the required mocking benefit without using any mocking framework. Then why we need one? If you have observed, for every test case, we need to use new class of the interface. If there are 10 test cases combinations, we need 10 classes. This will make the tests long and one needs to unnecessarily write lengthy classes even to use single method out of it.

Mocking framework does exactly the same as we did. It creates dummy class for interface we need to mock and return the values that we suggested. This suggestion is done though ‘Setup’ methods.

This prevents the user code from getting lengthy as the creation of mock classes is handled by framework itself. The framework returns the instance name which is used throughout test execution. So instead of creating instance of new mock class, we can just write Mock<IResult>.

So while using and debugging mocking you need to understand-

  1. Mocking is based on Inheritance mainly through interfaces. This is because, in interfaces all methods are virtual and mock can override them.
  2. Same principle for classes, only virtual methods can be altered through mocks, not all methods.
  3. Mocking of Static class is not possible as it can’t be inherited.
  4. You cannot mock system classes as they are mostly sealed.

Conclusion — Mocks are gifts for programmers as they make you visualize behavior of your class by stimulating coupled class’ output as you want.

--

--

Dipak Gawade

Software geek, blogger. Passionate about learning new concepts and share knowledge. Believe in 'lifetime understanding' than 'interview prep'.