Search code examples
c#testing.net-coremoq.net-core-3.0

.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


Solution

  • 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