Anna Melashkina
Anna Melashkina

Reputation: 472

NSubstitute: How to unit test LoggerMessageAttribute?

Previously I was logging with LogWarning and had tests like this:

var logger = Substitute.For<ILogger>();
// Do stuff...
logger.Received(1).Log(LogLevel.Warning, 0, Arg.Any<AnyType>(), null, Arg.Any<Func<AnyType, Exception?, string>>());

But since EventLogLogger is obsolete. I should use LoggerMessageAttribute.

How can I test, that logger was logging?

Upvotes: 0

Views: 113

Answers (1)

jessiebot
jessiebot

Reputation: 41

I'd recommend trying the .Net FakeLogger similar to the what is done in this blog post

FakeLogger loggerFake = new FakeLogger();
ILogger loggerMock = loggerFake;

//later
//Whatever you want to assert
Assert.That(loggerFake.Collector.GetSnapshot().Any(x => x.Level == LogLevel.Information), Is.True);

I found this to be a much easier approach than trying to roll my own ILogger mock.

Upvotes: 0

Related Questions