Using Xunit And Moq In .NET Core For Testing

Everyone wants to write bug free code, which is good, but the problem is there are a few bugs which are revealed at the time of integration or in the future after updating code that has dependencies.

Unit Tests help us prevent such situations right after you are done with your changes. UTCs cannot catch all the errors but they minimize the bugs from production

You can test your code with some sample data right after you write it. I have worked on software which has more than 10000 UTCs and most parts of the application can be tested using those UTCs only. These UTCs catch integration level errors or check some corner scenarios.

UTCs are as good as their writer. It all depends on how many scenarios you can cover and quality of Test Data.

It’s time for an example:

First, add a xUnit Test project in your solution,

This will create a UnitTest1.cs file in your project with Test1() method.

In xUnit project Fact and Theory are used in place of TestMethod attribute

Now it’s time to include moq nugget,

After importing it in your class you are all set for your first test method,

using Xunit;  
using CrossProjectDemo;  
using Moq;  
  
namespace Struts.Tests  
{  
    public class UnitTest1  
    {  
        [Fact]  
        public void Test1()  
        {  
            var moc = new Mock<CustomLoops>();  
            var car = new Car(moc.Object);  
            car.Caller(null, 9);  
        }  
    }  
}

Here you can see I am using Mock class to create a dummy object or class CustomLoops which is called mocking a class.

Let’s see what this moc variable has,

Now it's time to run the Mock the method as well

[Fact]  
public void Test1()  
{  
    var moc = new Mock<CustomLoops>();  
    moc.Setup(mc => mc.mockingMethod()).Returns(200);  
    var car = new Car(moc.Object);  
    car.Caller(null, 9);  
  
    Assert.Equal(200, car.mockingMethod());  
}

As you can see UTC ran successfully and Assert passed, Now see one thing

public virtual int mockingMethod()  
{  
    return 110;  
}

The mocking method is returning only 110. So how can the Assert pass?

In this example, I have mocked the method mockingMethod of CustomLoops class and returned 200 from it. To mock a method it must be virtual.

Now coming back to attributes. xUnit uses Fact and Theory as attribute to mark a method test.

Fact is used when you want to run a method only once.

Theory is used when you want to run a method multiple times.

You can use InlineData() attribute to pass various data to the test method.

Now you know you can mock classes and methods in .net using moq and xUnit. These are a very powerful library for TDD. With the use of dependency injection testing can be done more effectively and it also reduces dependency among projects. 

That’s it from this post

Thanks