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.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

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

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay