Skip to content

Instantly share code, notes, and snippets.

@dennyweiss
Forked from cknaap/SimpleLogCheck.cs
Created April 11, 2017 10:53
Show Gist options
  • Save dennyweiss/da3819c829990b18dc31bd1b5e8df970 to your computer and use it in GitHub Desktop.
Save dennyweiss/da3819c829990b18dc31bd1b5e8df970 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);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment