Skip to content

Instantly share code, notes, and snippets.

@changhuixu
Last active September 4, 2019 14:10
Show Gist options
  • Save changhuixu/7afaf0ad2be6d664f3fb86eb27895854 to your computer and use it in GitHub Desktop.
Save changhuixu/7afaf0ad2be6d664f3fb86eb27895854 to your computer and use it in GitHub Desktop.
Unit Testing with .NET Core ILogger<T>
public class CalculationService : ICalculationService
{
private readonly ILogger<CalculationService> _logger;
public CalculationService(ILogger<CalculationService> logger)
{
_logger = logger;
}
public int AddTwoPositiveNumbers(int a, int b)
{
if (a <= 0 || b <= 0)
{
_logger.LogError("Arguments should be both positive.");
return 0;
}
_logger.LogInformation($"Adding {a} and {b}");
return a + b;
}
}
public static class MockLoggerExtensions
{
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(level, It.IsAny<EventId>(), It.Is<object>(o => o.ToString() == message), null,
It.IsAny<Func<object, Exception, string>>()),
times, failMessage);
}
}
[TestMethod]
public void TestWithConsoleLogger()
{
using (var loggerFactory = new LoggerFactory().AddConsole()) // Need to use "using" in order to flush Console output
{
var logger = loggerFactory.CreateLogger<CalculationService>();
var svc = new CalculationService(logger);
var result = svc.AddTwoPositiveNumbers(1, 2);
Assert.AreEqual(3, result);
}
// The loggerFactory above is obsolete as of .NET Core 2.2.
// Please use the following method in .NET Core 3.0.
//using (var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole()))
//{
// var logger = loggerFactory.CreateLogger<CalculationService>();
// var svc = new CalculationService(logger);
// var result = svc.AddTwoPositiveNumbers(1, 2);
// Assert.AreEqual(3, result);
//}
}
[TestMethod]
public void TestWithDependencyInjectionLogger()
{
var services = new ServiceCollection()
.AddLogging(config => config.AddConsole()) // can add any logger(s)
.BuildServiceProvider();
using (var loggerFactory = services.GetRequiredService<ILoggerFactory>())
{
var svc = new CalculationService(loggerFactory.CreateLogger<CalculationService>());
var result = svc.AddTwoPositiveNumbers(1, 2);
Assert.AreEqual(3, result);
}
}
[TestMethod]
public void TestWithMockLogger()
{
var loggerMock = new Mock<ILogger<CalculationService>>();
var svc = new CalculationService(loggerMock.Object);
var result = svc.AddTwoPositiveNumbers(1, 2);
Assert.AreEqual(3, result);
loggerMock.VerifyLog(LogLevel.Information, "Adding 1 and 2");
result = svc.AddTwoPositiveNumbers(-1, 1);
Assert.AreEqual(0, result);
loggerMock.VerifyLog(LogLevel.Error, "Arguments should be both positive.", Times.Once());
}
[TestMethod]
public void TestWithNullLogger()
{
var svc = new CalculationService(new NullLogger<CalculationService>());
var result = svc.AddTwoPositiveNumbers(1, 2);
Assert.AreEqual(3, result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment