How to Unit Test with Ilogger in ASP.NET Core

How to unit test with ILogger in ASP.NET Core

Just mock it as well as any other dependency:

var mock = new Mock<ILogger<BlogController>>();
ILogger<BlogController> logger = mock.Object;

//or use this short equivalent
logger = Mock.Of<ILogger<BlogController>>()

var controller = new BlogController(logger);

You probably will need to install Microsoft.Extensions.Logging.Abstractions package to use ILogger<T>.

Moreover you can create a real logger:

var serviceProvider = new ServiceCollection()
.AddLogging()
.BuildServiceProvider();

var factory = serviceProvider.GetService<ILoggerFactory>();

var logger = factory.CreateLogger<BlogController>();

How do I provide ILoggerT in my unit tests of .NET Core code?

You have two options:

  1. Create empty implementation of ILogger<Foo> by hand and pass an instance of it to ctor.
  2. Create same empty implementation on the fly using some mocking framework like Moq, NSubstitute, etc.

ASP.NET Core 3.1 | How to make unit tests with service collection and use NullLogger as ILogger implementation

In order to add NullLogger to service collection and allow it's injecting into other services, you should add only the NullLoggerProvider instead of trying to add it like a singleton service.

_services.AddLogging(l => l.AddProvider(NullLoggerProvider.Instance));

Complete setup method:

[SetUp]
public void Setup()
{
_services = new ServiceCollection();
_services.AddLogging(l => l.AddProvider(NullLoggerProvider.Instance));
_services.AddSingleton<MyService>();
_serviceProvider = _services.BuildServiceProvider();
}

How to test asp.net core built-in Ilogger

As @Nkosi've already said, you can't mock an extension method. What you should mock, is the ILogger.Log method, which LogError calls into. It makes the verification code a bit clunky, but it should work:

MockLogger.Verify(
m => m.Log(
LogLevel.Error,
It.IsAny<EventId>(),
It.Is<FormattedLogValues>(v => v.ToString().Contains("CreateInvoiceFailed")),
It.IsAny<Exception>(),
It.IsAny<Func<object, Exception, string>>()
)
);

(Not sure if this compiles, but you get the gist)

Unit Testing Static Methods with ILogger in C# ILoggerFactory is Null

Thanks a lot to the comment off @ChetanRanpariya the answer to my question was really simple:

using NUnit.Framework;
using Microsoft.Extensions.Logging;
using System.Reflection;
using Moq;
using System;
using MyProgramVIP.Bots.Presenter;
using MyProgramVIP.Bots.Model;
using MyProgramVIP.Bots.Utils;

namespace MyProgramVIPTest
{
public class TestsExample
{
[SetUp]
public void Setup() {

}

[Test]
public void TestExample1()
{
//Mocks
var mockLogger = new Mock<ILogger<TicketPresenter>>();
mockLogger.Setup(
m => m.Log(
LogLevel.Information,
It.IsAny<EventId>(),
It.IsAny<object>(),
It.IsAny<Exception>(),
It.IsAny<Func<object, Exception, string>>()));

var mockLoggerFactory = new Mock<ILoggerFactory>();
mockLoggerFactory.Setup(x => x.CreateLogger(It.IsAny<string>())).Returns(() => mockLogger.Object);

//Just add this, I guess is replacing the objet with the mock.
UtilsVIP.ApplicationLogging.LoggerFactory = mockLoggerFactory.Object;

//Construción del modelo necesario para la prueba
ConversationData conversationData = new ConversationData();
conversationData.ticket = new Ticket();
conversationData.response = new Response();

//Invocación del método a probar
TicketPresenter.getPutTicketMessage(conversationData);

//Comprobación del funcionamineto
Assert.AreEqual("ticketType", conversationData.response.cardIdResponse);
}
}
}

Just add this:

UtilsVIP.ApplicationLogging.LoggerFactory = mockLoggerFactory.Object;

Thanks for the help.



Related Topics



Leave a reply



Submit