As logger.LogError()
or logger.LogInformation()
are extended method, we cannot directly mock these methods.
According to this stackoverflow, we can mock it by using underline method with little trick.
Unit Test logger.LogError
This is how I write unit test for logger.LogError
to be called only once.
The Log method takes FormattedLogValues
class instance in third argument, which is internal class, thus I couldn't instantiate it. Therefore I use It.IsAny<It.IsAnyType>()
.
Mock<MyService> mockedMyService = new();
mockedILogger.Verify(x => x.Log(
LogLevel.Error,
It.IsAny<EventId>(),
It.IsAny<It.IsAnyType>(),
It.IsAny<Exception>(),
It.IsAny<Func<It.IsAnyType, Exception?, string>>()),
Times.Once);
Other extension methods such as LogWarning
, LogInformation
shall work in the same manner.
Top comments (0)