Home > other >  c# nUnit, log mock verify doesn't work where is called for multiple time in the code
c# nUnit, log mock verify doesn't work where is called for multiple time in the code

Time:03-21

I am working on .NET CORE 3.1 nUnit tests and trying to verify log. I have notice that log that call single time does recognize and work and if same log in loop for example log.logDebug when record does not exist does not work with verify code.

log is instance of ILogger mock

class

log.LogDebug("No files discovered in testing....");

Test

_loggerMoq.Verify(
            x => x.Log(
                LogLevel.Debug,
                It.IsAny<EventId>(),
                It.Is<It.IsAnyType>((o, t) => string.Equals("No files discovered in testing....", o.ToString(), StringComparison.InvariantCultureIgnoreCase)),
                It.IsAny<Exception>(),
                It.IsAny<Func<It.IsAnyType, Exception, string>>()),
            Times.Once);

CodePudding user response:

You have to change It.IsAny<Func<It.IsAnyType, Exception, string>>()), to (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()),

Not sure why this works, it is a known bug in the Moq library.

CodePudding user response:

_loggerMoq.Verify(
            x => x.Log(
                LogLevel.Debug,
                It.IsAny<EventId>(),
                It.Is<It.IsAnyType>((o, t) => string.Equals("No files discovered in testing....", o.ToString(), StringComparison.InvariantCultureIgnoreCase)),
                It.IsAny<Exception>(),
                (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()),
            Times.AtLeastOnce());
  • Related