DEV Community

Kenichiro Nakamura
Kenichiro Nakamura

Posted on

C#: How to unit test ILogger?

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);
Enter fullscreen mode Exit fullscreen mode

Other extension methods such as LogWarning, LogInformation shall work in the same manner.

Top comments (0)