DEV Community

Juarez Júnior
Juarez Júnior

Posted on

Unit Testing with Mocks Using Moq

Moq is a mocking library for .NET that simplifies the creation of unit tests by allowing the simulation of behaviors and dependencies. It is widely used to create “mocks” of interfaces or complex objects, enabling you to isolate business logic in your tests. Moq is easy to use and helps test scenarios that depend on external services, databases, or APIs. In this example, we will create a unit test simulating the behavior of an interface using Moq.

Libraries:

To use the Moq library, install the following NuGet package in your project:

Install-Package Moq
Enter fullscreen mode Exit fullscreen mode

Example Code:

using Moq;
using System;
using Xunit;

// Interface to be mocked
public interface ICalculator
{
    int Add(int a, int b);
}

// Class that uses the interface
public class Operations
{
    private readonly ICalculator _calculator;

    public Operations(ICalculator calculator)
    {
        _calculator = calculator;
    }

    public int ExecuteSum(int a, int b)
    {
        return _calculator.Add(a, b);
    }
}

public class OperationsTests
{
    [Fact]
    public void ExecuteSum_ShouldReturnCorrectSum()
    {
        // Creating the mock for the ICalculator interface
        var mockCalculator = new Mock<ICalculator>();

        // Defining the expected behavior for the Add method
        mockCalculator.Setup(c => c.Add(2, 3)).Returns(5);

        // Using the mock in the Operations class
        var operations = new Operations(mockCalculator.Object);
        var result = operations.ExecuteSum(2, 3);

        // Verifying if the result is as expected
        Assert.Equal(5, result);

        // Verifying if the Add method was called exactly once
        mockCalculator.Verify(c => c.Add(2, 3), Times.Once);
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

In this example, we create an interface called ICalculator with a Add method. Then, we create the Operations class, which uses this interface. In the unit test ExecuteSum_ShouldReturnCorrectSum, we use Moq to create a “mock” of the ICalculator interface, defining that when the Add method is called with the parameters 2 and 3, it should return 5. The test checks if the result is as expected and if the Add method was called once.

Conclusion:

Moq is a powerful tool for creating mocks and simplifying unit tests. It allows you to simulate complex behaviors, making it easier to isolate business logic and ensuring that your tests focus on core functionality without relying on real implementations.

Source code: GitHub

Top comments (0)