Moq Mocking Framework With xUnit.net Unit Test In C#

What are Mocking Frameworks? 

Mocking Frameworks (Moq, NSubstitute, Rhino Mocks, FakeItEasy, and NMock3) are used to create fake objects. We can stub, i.e., completely replace the body of member and function. It is used to isolate each dependency and help developers in performing unit testing in a concise, quick, and reliable way.

Creating mock objects manually is very difficult and time-consuming. So, to increase your productivity, you can go for the automatic generation of mock objects by using a Mocking Framework. A developer can build his/her unit test by using any of the NUnit, MbUnit, MSTest, xUnit etc. unit test frameworks.

Description

In this article, we will configure Moq Mocking Framework with xUnit.net unit testing framework.

Prerequisite
Step 1

Create a library project ("TDD.xUnit.net.Client") and set up xUnit.net unit test project. If you are not aware of setting up Xunit unit test project, then refer to the article - Setup xUnit.net Unit Testing In Class Library Project.

Step 2

Create a library project ("Calculator.Lib") and a test project ("TDD.xUnit.net.Client") as in the following screen.

Moq Mocking Framework With xUnit.net Unit Test In C#

Step 3

Open "ICalculator.cs" file from "Calculator.Lib" project and add the following lines of code.
  1. namespace CalculatorLib  
  2. {  
  3.     public interface ICalculator  
  4.     {  
  5.         decimal Add(decimal num1, decimal num2);  
  6.         decimal Substract(decimal num1, decimal num2);  
  7.         decimal Multiply(decimal num1, decimal num2);  
  8.         decimal Divide(decimal num1, decimal num2);  
  9.     }  
  10. }  
Step 4

So far, we have not implemented interface "ICalculator.cs". Now, let's try to write a unit test case. What do you think? Is it possible to write a unit test case for ICalculator interface without using a mocking framework? Think for a while! No, absolutely not, because you cannot create an instance of an interface so you can't write a unit test for the interface without a mocking framework.

Step 5

Open "CalculatorTests.cs" file from "TDD.xUnit.net.Client" project and add the following lines of code. 
  1. using CalculatorLib;  
  2. using System.Diagnostics.CodeAnalysis;  
  3. using Xunit;  
  4.   
  5. namespace TDD.xUnit.net.Client  
  6. {  
  7.     [ExcludeFromCodeCoverage]  
  8.     public class CalculatorTests  
  9.     {  
  10.         [Fact]  
  11.         public void PassingTest()  
  12.         {  
  13.             var calculator = new ICalculator();  
  14.             Assert.Equal(4, calculator.Add(2, 2));  
  15.         }  
  16.     }  
  17. }   
Moq Mocking Framework With xUnit.net Unit Test In C# 
 
Step 6

Now, let us install the Moq Mocking Framework. You can install this either by running a command in Package Manager Console or just by searching NuGet Package Manager. Let's install it by Package Manager Console by running the below command. 
  1. Install-Package Moq -Version 4.9.0   
Moq Mocking Framework With xUnit.net Unit Test In C# 
 
From the above screen, you can see Moq mocking framework which has been installed in the highlighted project. Now, let's write the unit test for interface ICalculator.
 
Step 7

Open "CalculatorTests.cs" file from "TDD.xUnit.net.Client" project and replace the following lines of code.
  1. using CalculatorLib;  
  2. using Moq;  
  3. using System.Diagnostics.CodeAnalysis;  
  4. using Xunit;  
  5.   
  6. namespace TDD.xUnit.net.Client  
  7. {  
  8.     [ExcludeFromCodeCoverage]  
  9.     public class CalculatorTests  
  10.     {  
  11.         [Fact]  
  12.         public void PassingTest()  
  13.         {  
  14.             //var calculator = new ICalculator();  
  15.             //Assert.Equal(4, calculator.Add(2, 2));  
  16.   
  17.             var calculator = new Mock<ICalculator>();  
  18.             calculator.Setup(x => x.Add(2, 2)).Returns(4);  
  19.             Assert.Equal(4, calculator.Object.Add(2, 2));  
  20.         }  
  21.     }  
  22. }  

Now, you can see we are able to write, debug, and run the unit test case as in the below screen.

Moq Mocking Framework With xUnit.net Unit Test In C#
 
What are the other options except for mocking framework? Here, you can create a fake object manually without using the mocking framework. You can create FakeCalculator class just by inheriting ICalculator class. Let's create a fake object manually. 
 
Step 8

Open "FakeCalculator.cs" file from "Calculator.Lib" project and add the following lines of code.
  1. using System;  
  2.   
  3. namespace CalculatorLib  
  4. {  
  5.     public class FakeCalculator : ICalculator  
  6.     {  
  7.         public decimal Add(decimal num1, decimal num2)  
  8.         {  
  9.             return num1 + num2;  
  10.         }  
  11.   
  12.         public decimal Divide(decimal num1, decimal num2)  
  13.         {  
  14.             throw new NotImplementedException();  
  15.         }  
  16.   
  17.         public decimal Multiply(decimal num1, decimal num2)  
  18.         {  
  19.             throw new NotImplementedException();  
  20.         }  
  21.   
  22.         public decimal Substract(decimal num1, decimal num2)  
  23.         {  
  24.             throw new NotImplementedException();  
  25.         }  
  26.     }  
  27. }   
This is how you can create a fake object as above. We implemented the body of "Add" method, only the rest of the methods did not implement as in "FakeCalculator" class.
 
Step 9

Open "CalculatorTests.cs" file from "TDD.xUnit.net.Client" project and add the following lines of code.
  1. using CalculatorLib;  
  2. using Moq;  
  3. using System.Diagnostics.CodeAnalysis;  
  4. using Xunit;  
  5.   
  6. namespace TDD.xUnit.net.Client  
  7. {  
  8.     [ExcludeFromCodeCoverage]  
  9.     public class CalculatorTests  
  10.     {  
  11.           
  12.         [Fact]  
  13.         public void AddTest()  
  14.         {  
  15.             var calculator = new FakeCalculator();  
  16.             Assert.Equal(5, calculator.Add(2, 3));  
  17.         }  
  18.   
  19.         [Fact]  
  20.         public void MultiplyTest()  
  21.         {  
  22.             var calculator = new FakeCalculator();  
  23.             Assert.Equal(6, calculator.Multiply(2, 3));  
  24.         }  
  25.   
  26.         [Fact]  
  27.         public void PassingTest()  
  28.         {  
  29.             //var calculator = new ICalculator();  
  30.             //Assert.Equal(4, calculator.Add(2, 2));  
  31.   
  32.             var calculator = new Mock<ICalculator>();  
  33.             calculator.Setup(x => x.Add(2, 2)).Returns(4);  
  34.             Assert.Equal(4, calculator.Object.Add(2, 2));  
  35.         }  
  36.     }  
  37. }  

We have written three unit tests for addition, multiplication, and mock tests. Now, let's try to run these unit tests and observe.

Moq Mocking Framework With xUnit.net Unit Test In C# 
 
Moq Mocking Framework With xUnit.net Unit Test In C# 
 
You can see that from the above screen, we cannot write a meaningful unit test for not-implemented methods without a mock test framework. Now, let's try to write the unit test cases for implemented and not implemented methods with a mock testing framework.

Note
Using Moq mocking framework, we can mock and stub only virtual or abstract methods. This is the limitation of the Moq mocking framework. If you try to mock or stub virtual and abstract methods you will get the exception as below screen.

Moq Mocking Framework With xUnit.net Unit Test In C# 

Now, let us add the virtual keyword in methods to make the method virtual and let's see the output of unit testing.

Step 10

Open "FakeCalculator.cs" file from "Calculator.Lib" project and add a virtual keyword to "Multiply" method as in the following lines of code.
  1. using System;  
  2.   
  3. namespace CalculatorLib  
  4. {  
  5.     public class FakeCalculator : ICalculator  
  6.     {  
  7.         public decimal Add(decimal num1, decimal num2)  
  8.         {  
  9.             return num1 + num2;  
  10.         }  
  11.   
  12.         public decimal Divide(decimal num1, decimal num2)  
  13.         {  
  14.             throw new NotImplementedException();  
  15.         }  
  16.   
  17.         public virtual decimal Multiply(decimal num1, decimal num2)  
  18.         {  
  19.             throw new NotImplementedException();  
  20.         }  
  21.   
  22.         public decimal Substract(decimal num1, decimal num2)  
  23.         {  
  24.             throw new NotImplementedException();  
  25.         }  
  26.     }  
  27. }  

Step 11

Now, let's run all the unit tests and observe.

Moq Mocking Framework With xUnit.net Unit Test In C# 
 
Now, you can see from the above screen, we are able to debug and run all unit test cases and errors.
 
There are many advantages if you use the Moq mocking testing framework instead of a real one or without mocking framework. There are two types of groups - the first ones love to write real unit tests without using any mocking framework and others love to write mock unit tests with mocking testing framework. Each group has their own logic, and pros and cons behind this belief. 
 
Real Unit Tests Writer Group

They believe that we are testing real objects instead of the fake or mock object so I also understand this belief.
 
Moq Unit Tests Writer Group
This group believes we should not write unit tests of real objects, as in the unit test we are only testing the piece of code, not the entire object. In the real object there should be complex dependencies, for example network, database, and unmanaged code. These objects are very expensive and time-consuming and if these object services go down then your entire unit test will fail since it is time-consuming, so it would discourage you to write fast and reliable and available unit tests. One more point here is, we are writing unit tests, not integration tests;  both are different. If we write real unit tests then somehow we are writing the integration test, not the unit test.
 
What I believe

We should use both real and moq unit tests to get the best results. We should write real unit test cases for none dependent or no dependencies (database, network, and unmanaged code) objects and for dependent objects, we should use moq tests. In this way we can minimize the complexity of dependency and it would allow writing more available, reliable and fast unit test cases. I hope you guys have learned about Moq mocking framework.

Step 11 - Done.

Congratulations! You have successfully learned what Moq is and how to configure Moq mocking framework in C#. If you have any query or concern, just let me know or just put it in the comment box and I will respond as soon as possible. I am open to discussing anything, even silly questions as well. If you have any suggestions related to this article, please let me know and I promise I will improve this article to a maximum level.

Summary

In this article, we have learned what is Moq and how to configure Moq mocking framework in C#.