Home
Tags:

Mocking with Moq

It enables you to isolate the code being tested by simulating the behaviour of dependencies, such as services or repositories, without requiring their actual implementations.

Naming conventions:

  • Either with a prefix: var mockService = ...
  • Or suffix: var serviceMock = ...

Links:

Mock out a dependency - Setup

using Moq;

public interface ICalculator
{
    int Add(int a, int b);
    int Subtract(int a, int b);
}
var mockCalculator = new Mock<ICalculator>();
mockCalculator.Setup(m => m.Add(It.IsAny<int>(), It.IsAny<int>())).Returns(5);

Check the mock was executed as part of the test. Verify

Moq Verify: Used to check that a method on a mock object was called as expected.

Verification: Moq allows you to verify that certain methods were called on the mock objects during the test.

[TestMethod]
public void Reverse_ShouldInvokeOnce_IsLogEnabled()
{
    _wordUtils.Reverse("mountain");

    Mock.Get(_log).Verify(x => x.IsLogEnabled(), Times.Once);
}

Throw an exception

//Throw an exception
mockAddressBuilder.Setup(m => m.From(It.IsAny<CustomerDto>())).Throws<InvalidAddressException>();

Installation

Powershell

Install-Package Moq