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>())
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:
- Unit Test and Mock Logger Methods in .NET Core
- Unit Testing Best Practices -Test-Driven Development
- Unit Testing Vs Intergration Best Practices -Test-Driven Development
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.
My project migrates from net core 2 to 3, just as you mentioned. Helped a lot! Thank you
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
Hi Lan,
Good day!
Thank you!. Glad the article helped you!