Skip to content

Instantly share code, notes, and snippets.

@cknaap
Last active December 17, 2021 22:11
Show Gist options
  • Save cknaap/6919df54820853f7a3ef054303cebfc3 to your computer and use it in GitHub Desktop.
Save cknaap/6919df54820853f7a3ef054303cebfc3 to your computer and use it in GitHub Desktop.
Easily check ILogger<T> interactions with ASP.NET Core Logging and Moq
using Microsoft.Extensions.Logging;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Knaap.Utilties
{
public class SimpleLogCheck
{
[Fact]
public void TestLog()
{
var loggerMock = LoggerUtils.LoggerMock<SimpleLogCheck>();
loggerMock.Object.LogInformation("test");
loggerMock.VerifyLog(LogLevel.Information, "test");
}
}
public static class LoggerUtils
{
public static Mock<ILogger<T>> LoggerMock<T>() where T : class
{
return new Mock<ILogger<T>>();
}
/// <summary>
/// Returns an <pre>ILogger<T></pre> as used by the Microsoft.Logging framework.
/// You can use this for constructors that require an ILogger parameter.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static ILogger<T> Logger<T>() where T : class
{
return LoggerMock<T>().Object;
}
public static void VerifyLog<T>(this Mock<ILogger<T>> loggerMock, LogLevel level, string message, string failMessage = null)
{
loggerMock.VerifyLog(level, message, Times.Once(), failMessage);
}
public static void VerifyLog<T>(this Mock<ILogger<T>> loggerMock, LogLevel level, string message, Times times, string failMessage = null)
{
loggerMock.Verify(l => l.Log<Object>(level, It.IsAny<EventId>(), It.Is<Object>(o => o.ToString() == message), null, It.IsAny<Func<Object, Exception, String>>()), times, failMessage);
}
}
}
@robert-fahey
Copy link

Didn't work for me

Moq.MockException :
Expected invocation on the mock once, but was 0 times: l => l.Log(LogLevel.Information, It.IsAny(), It.Is(o => o.ToString() == "test"), null, It.IsAny<Func<object, Exception, string>>())

Performed invocations:

Mock<ILogger:1> (l):

  ILogger.Log<FormattedLogValues>(LogLevel.Information, 0, test, null, Func<FormattedLogValues, Exception, string>)

at Moq.Mock.Verify(Mock mock, LambdaExpression expression, Times times, String failMessage)
at Moq.Mock1.Verify(Expression1 expression, Times times, String failMessage)
at CtCore.Email.Test.Common.Utils.LoggerUtils.VerifyLog[T](Mock`1 loggerMock, LogLevel level, String message, Times times, String failMessage) in D:\ct.git\secure-document-vault\ctcore-email\CtCore.Email.Test.Common\Utils\LoggerUtils.cs:line 31

Copy link

ghost commented Mar 19, 2020

Didn't work for me

This worked for me. Notice that I decided to use Contains instead of equal but that should not affect the result. If something does not match starting from message text to signature it will say 0 occurences. I took me some time to find the solution.

         loggerMock.Verify(
            x => x.Log(
                level,
                It.IsAny<EventId>(),
                It.Is<It.IsAnyType>((o, t) => o.ToString().Contains(message)),
                It.IsAny<Exception>(),
                (Func<It.IsAnyType, Exception, string>) It.IsAny<object>()),
            times);

@WolfyUK
Copy link

WolfyUK commented May 18, 2020

Thanks, @aperisic. Your solution works for .NET Core 3.1. The original solution worked for .NET Core 2.1 but failed after migration to v3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment