How to verify that method was NOT called in Moq?

Today in this article, we will see programmatically verify that method was NOT called in Moq or method invocation is more than 1 or equal to of expected invocation times.

While performing unit test cases or functional test execution, sometimes it’s beneficial to know if particular logic or method was called or not. Especially in business-critical test cases, you may want to go crazy about how much validation you want to add to verify a scenario. This might help in addressing the quality of test cases written and provide additional validation steps.

We will use the below example where we will verify if the Logging method execution happened within the business logic or not.

Below is the sample example that we are calling Lognformation() and LogError().

So above we will verify for a valid scenario if LogError() is not called and same time Lognformation() is called 2 times.

How to verify that method was NOT called in Moq

Let’s write Unit test cases as below,

        [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);
            Assert.Equal(expectedResult, result.Value);

            _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));
      
        }

Verify that method was NOT called in Moq

You can use XUnit with Moq mock support methods if logger methods are called Once or Twice, etc.

One can use the below code to achieve the same,

As I verified, the below code works for ASP.NET Core 3.1 or .NET 5 also,

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

The above code is verifying if the LogError method was not called i.e called 0 times.

Verify that method was called 1 or ‘n’ times in Moq

The below code is validating that the LogInformation is getting called 2 times in a given method.

 _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));

This is useful when you are making sure developers don’t miss to call logging at least 2 times i.e start and at end of the method call. Very useful indeed for debugging and troubleshooting purposes in lower environments.

The above code matches with the below-overloaded Log method template,

Verify method invocation in XUnit Moq

References :


Do you have any comments or ideas or any better suggestions to share?

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.



Leave a Reply

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