Log Error: Expected invocation on the mock exactly times, but was 0 times

Issue Description

The unit testing logger method produces errors while mocking logger extension methods using Moq.

Moq.MockException: Expected invocation on the mock exactly 2 times, but was 0 times: m => m.Log(LogLevel.Information, It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>())

Log Error Expected invocation on the mock exactly times but was 0 times

The above error was mostly observed while mocking logger extension methods .NET Core 3.0 and above version.

This error could also exist if migrating .NET Core 2.* code to .NET Core 3.* code

Resolution

The issue found seems to be due to the new generic type support introduced in the recent version of the Moq test framework.

I was able to fix the error using the below code base.

 [Fact]                 
        public void BookService_Get_ValidBookID_Success()
        {
            //Arrange
            var _mockBusiness = new Mock<IBusinessLayer>();
            var _mockLogger = new Mock<ILogger<ValuesController>>();
            int input = 12;
            int expectedloggerInvocationCount = 2;
            string expectedResult = "True";
            _mockBusiness.Setup(x => x.PerformBusiness()).Returns(true);

            //Act

            ValuesController controller = new ValuesController(_mockLogger.Object, _mockBusiness.Object);
            var result = controller.Get(input).Result as ObjectResult;

            //Assert

            Assert.Equal(HttpStatusCode.OK, (HttpStatusCode)result.StatusCode);

            _mockLogger.Verify(x => x.Log(LogLevel.Information,
               It.IsAny<EventId>(),
               It.IsAny<It.IsAnyType>(),
               It.IsAny<Exception>(),
               (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()),
               Times.Exactly(2));
     }

Alternatively,

If you still get any compatibility issues, use the below code to verify method invocation. The below code does the same job as Verify methods.

Assert.Equal(2, _mockLogger.Invocations.Count)

References:

Did I miss anything else in these resolution steps?

Did the above steps resolve your issue? Please sound off your comments below!

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



3 thoughts on “Log Error: Expected invocation on the mock exactly times, but was 0 times

  1. I have the same error in my TU (xunit with Moq):
    Expected invocation on the mock exactly 2 times, but was 0 times

    and your solution is perfect !!! It works 🙂
    Thanks very much

    Lan

Leave a Reply

Your email address will not be published. Required fields are marked *