Implementing Unit Test .Net Core Application Using CQRS Handler

What is testing?

Testing is an integral part of development now, and the expectation from developers is to make their code robust, and rigorous testing is one way to do it.

There are different types of testing.

  • Unit Testing
  • Integration Testing
  • System Testing

The unit testing tests a specific piece of the program, and everything else is mocked.

The integration test is larger in scope and tests multiple components together and, most of the time, a complete scenario.

The system testing is testing the whole system and running a complete scenario.

In this article, we are going discuss how to test your .Net Core API Project.

Before jumping into the implementation, we should know that there are different testing frameworks available in the .Net world. Some of them are.

  • XUnit
  • NUnit
  • MsTest

We are going to use XUnit as it could be considered as the superset of NUnit.

XUnit Implementation

The API application for which I will be writing the unit test is based on CQRS architecture, but the Unit test is mostly independent of the architecture as we mock the dependency and test the relevant piece of code only.

First, create a Unit test project in your application.

Project templete

Now I have a service that gets orders according to the status, we will create a test Class for writing unit test in it.

New item

It is a Convention to use before the component name we are testing.

First, Define the test.

public class OrderShould
{
    public OrderShould()
    {
    }

    [Fact]

    public async Task GetUserBy_Status()
    {
        //Assign
        //Act
        // Assert
    }
}

AAA is the approach we will use.

First, we arrange all the required elements we need to test our code.

Second, we perform the action we wanted to test.

Third, we check If we got the required result.

There are different types of Unit tests. We are writing Facts and will implement Theory in a later example.

The code we are testing is using Repository so we will mock the repository.

Mocking Object

Mocking is the approach of using the mock object instead of actual dependency.

Create a Moq folder and Create a Moq Class.

MOQ

public class OrderManagerMoq
{
    public static IOrderRepository GetOrderRepository()
    {
        var moq = new Mock<IOrderRepository>();
        moq.Setup(x => x.GetOrderByStatus(It.IsAny<string>())).Returns(Orders);
        return moq.Object;
    }
    public static List<Order> Orders = new List<Order>()
    {
        new Order()
        {
            OrderNumber = 1,
            orderStatus = new OrderStatus()
            {
                Id = 1,
                Value = "Pending",
            }
        },
        new Order()
        {
            OrderNumber = 2,
             orderStatus = new OrderStatus()
            {
                Id = 1,
                Value = "Pending",
            }
        }
    };
}

Now we will implement the unit test as we have all the required elements.

private IOrderRepository _repository;
private GetOrderByStatusHandler _orderhandler;
public OrderShould() {
_repository = OrderManagerMoq.GetOrderRepository();
_orderhandler = new GetOrderByStatusHandler(_repository);
}

[Fact]
public async Task GetUserBy_Status()
{
    //Assign
    var request = new GetOrderByStatusRequest() { status = "Pending" };
    var token = new CancellationToken();
    //Act
    var result = await _orderhandler.Handle(request,token);
    // Assert
    Assert.NotNull(result);
}

Now, In theory, we can provide the inline sample data to test our code.

We can pass complete objects too.

[Theory]
[InlineData("7a508c2e-d9b1-41c2-86bb-de48ddb0ca42")]
public async Task Users_GetAllUsersById(string id)
{
    // Assign
    var request = new GetUsersByIdRequest()
    {
        Id = id
    };
    var token = new CancellationToken();
    //Action
    var result =  await _userbyIdhandler.Handle(request, token);
    //Asset
    Assert.Equal(result.Id,id);
}


Similar Articles