Pawel
Pawel

Reputation: 624

.NET Core 3.0 ILogger testing

I just migrated from .NET Core 2.2 to .NET Core 3.0 and... My tests have failed.

Below code is working in .NET Core 2.2 but is failing in .NET Core 3.0 with

Expected invocation on the mock once, but was 0 times: l => l.Log<object>(LogLevel.Error, 0, It.IsAny<object>(), null, It.IsAny<Func<object, Exception, string>>())

var services = Mock.Of<IServiceCollection>();
var configurationMock = new Mock<IConfiguration>();
var loggerMock = new Mock<ILogger>();

services.AddCustomersConfiguration(configurationMock.Object, loggerMock.Object);

configurationMock.Verify(c => c.GetSection(Customers), Times.Once);
loggerMock.Verify(l => l.Log<object>(LogLevel.Error, (EventId)0, It.IsAny<object>(), null, It.IsAny<Func<object, Exception, string>>()), Times.Once);

Implementation of used method

public static void AddCustomersConfiguration(this IServiceCollection services, IConfiguration configuration, ILogger logger)
{
    logger.LogDebug($"Entering {nameof(AddCustomersConfiguration)} method.");
    var customersSection = configuration.GetSection(CustomersSectionKey);
    if (!customersSection.Exists())
    {
        logger.LogError($"There is no {CustomersSectionKey} section in configuration.");
        return;
    }
}

That would be helpful if you would have any suggestions

Upvotes: 1

Views: 306

Answers (2)

rgvlee
rgvlee

Reputation: 3193

In addition to the accepted answer, consider strengthening the assert to include the log message

loggerMock.Verify(l => l.Log(
                LogLevel.Error, 
                It.IsAny<EventId>(),
                It.Is<It.IsAnyType>((o, t) => ((IReadOnlyList<KeyValuePair<string, object>>)o).Last().Value.ToString().Equals(expectedLogMessage)),
                null, 
                (Func<It.IsAnyType, Exception, string>) It.IsAny<object>()), 
                Times.Once);

The last item of the logged values (key: OriginalMessage) has the message that was provided to the log method.

Upvotes: 1

Nkosi
Nkosi

Reputation: 247323

I was able to reproduce the error and identified the problem via similar found issues for this version of .Net Core

With the recent version of Moq and the introduction of It.IsAnyType, replacing the verification with

loggerMock.Verify(l => l.Log(LogLevel.Error, (EventId)0, It.IsAny<It.IsAnyType>(), 
    null, (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()), Times.Once);

worked as expected.

Reference https://github.com/moq/moq4/issues/918

Upvotes: 2

Related Questions