C# Unit Testing with Moq

Moq Unit Test C#
Share this

In this article, you will learn how to perform C# unit testing with Moq which is a popular and friendly open source mocking framework.

Mock objects are simulated objects that mimic the behavior of real objects. Mock objects are a way to simulate an object that you need to work with. You can come across situations or states that are difficult to reproduce.

For example – you want to write unit tests for a web service. In the unit test, you call the web service but the web service is down for some reason or the service doesn’t return the same value for the same input parameters. In this case, you unit test will fail as the Asserts you define won’t be equal to the value you pass.

Mocking framework come to a rescue here. You can mock the web service call.

I will write unit tests for Web API Controller methods. I will be refactor code from my previous post to implement Repository Pattern and use Constructor Dependency Injection to inject repository as a dependency in the Controller. I am using MSTest as the unit testing framework and a library Moq (which can be added as a reference to the unit test project using NuGet) to mock repository class.

Source Code : Complete source code for the article can be found on GitHub repo :


Unit Test vs Integration Test :

Let us clearly understand the difference between Unit Test and Integration Test. If I had written a test method which inserts test data in the CI (Continuous Integration) database in method marked with [TestInitialize], asserts against that data and finally deletes the inserted data in method marked with [TestCleanUp] attribute, this would be an integration test and not an unit test. These tests would also take a lot of time to execute as they are making the database calls and considering your CI build will be building the code and executing all the unit tests will make the CI build very slow.

A true unit test is one where you don’t have any external dependencies on any external systems for services like database or web services etc.

Now the question is if you have the controller methods interacting with the database using an ORM like Entity Framework etc. via a repository class, how can you write a unit test which calls these Controller’s methods without making the database calls. Here a mocking framework like Moq comes to a rescue where you mock the repository methods and call those mocked methods from the Controller.

Code changes to be made in the previous article’s code. If you haven’t read the previous article and don’t want to get into the details of Angular 4 and want to learn how to write Unit Tests in C# using a mocking library like Moq, you can directly jump to (2) Create C# Unit Tests below.

(1) Implement Repository Pattern

In the first step, we will refactor the earlier Web Api Controller’s code to implement the repository pattern.

At the application root under the Visual Studio solution, add a new folder named “Repository”. Add a new Interface IProductRepository.cs with the following code.

Next, create a class ProductRepository.cs with the code as shown below.

Next, refactor the existing WebApi controller ProductController.cs file’s code as shown below.

Next, change the web api call’s for adding product and updating product in the Angular 4 dataservice.ts file’s methods as shown below.

This completes the code changes needed to implement the Repository pattern.

(2) Create C# Unit Tests

If you didn’t add an unit test project while creating the WebApi project, you can do that now by right clicking the Solution and selecting Add -> New Project -> Unit Test Project (.NET Framework). Name the project as Angular4WebApi.Tests and save it. Delete the default UnitTest1.cs file and add a new Unit Test file with the name Angular4WebApiTests.cs with the following code.

In the above code, global variables are declared at the top of the unit test class. Then the InitializeTestData() method marked with [TestInitialize] attribute initializes the test data and mocks the IProductRepository.cs class methods for Listing all products, Adding a new product, Updating an existing product and Deleting an existing product.

Next are defined various ‘Test Case’ methods for Listing all products, Adding a new product, Updating an existing product and Deleting an existing product.

The commented code in these methods shows how to call the mocked repository method’s directly. But that’s now what you are supposed to do. You need to call the mocked repository methods from the controller like the controller call’s the actual repository methods which is shown in the very next line of the commented code.

Finally, the CleanUpTestData() method marked with [TestCleanUp] attribute deletes the test data.

Following screenshot shows the unit test execution results.


Following screenshot shows the unit test code coverage results.


Hope you followed the article. If you have any comments, questions or suggestions, leave a message and I will try to respond at my earliest.

Share this

Leave a Reply