Moq library 4.5 and above supports mocking objects in net Core. This article explains the step by step process that needed to Moq an object in net core. Mocking objects comes in handy when unit testing data store, where a Database can be mocked so that no data is added or modified in Database while unit testing source code.

Creating a test project

For the simplicity of explaining, I’m started with creating a XUnit test project in Visual Studio 2017 15.3

Add Moq package into the project

Moq version 4.5 and above support net core, at the time of writing this article the latest Moq was 4.7.99. Run following command in package manager command prompt or add using Nuget package manager.

Install-Package Moq

Create tests

Implement a dependency, create a program and inject dependency into the project. Below sample code implements a Calculator application and a Math library dependency.

Note that the “Add” function in MathLib is throwing a “Not implemented exception”. The

using Moq;
using System;
using Xunit;

namespace MockingObject
{
    public interface IMathLib
    {
        int Add(int number1, int number2);
    }
    public class MathLib : IMathLib
    {
        public int Add(int number1, int number2)
        {
            throw new NotImplementedException();
        }
    }
    public class Calculator
    {
        private IMathLib _mathLib;

        public Calculator(IMathLib mathLib)
        {
            _mathLib = mathLib;
        }

        public int AddNumbers(int n1, int n2)
        {
            return _mathLib.Add(n1, n2);
        }
    }
    public class SutCalculator
    {
        [Fact]
        public void AddNumbersVerifyReturnsSum()
        {
            var mockedMathLib = new Mock<IMathLib>();
            mockedMathLib.Setup
            (
                fn => fn.Add
                (
                    It.IsAny<int>(), 
                    It.IsAny<int>()
                )
            ).Returns(4);
            var calculator = new Calculator(mockedMathLib.Object);

            Assert.Equal(4, calculator.AddNumbers(2, 2));
        }
    }
}

Run tests

The tests can be run in two ways.

  • Run using dotnet CLI
    1. In a command prompt, navigate to the folder where .csproj file of test project resides and run dotnet test command
  • Visual Studio test explorer
  • Navigate to “Test Menu” and click on “Windows” menu item and select “Test Explorer“. On the Test Explorer pane, select “Run All“.