DEV Community

Kenichiro Nakamura
Kenichiro Nakamura

Posted on

8 1

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs