3

I am trying to use nsubstitute to test the ILogger in Microsoft.Extensions.Logging. Just as here says: Cannot test ILogger<T> Received with NSubstitute , at that time, nsubstitute has no something like It.IsAnyType in Moq, I want to know whether nsubstitute has the similar thing now? as I am also work on unit test based on nsubstitute. @rgvlee's sample:

public class TestsUsingMoq
{
    [Test]
    public void MyMethod_String_LogsError()
    {
        // Arrange
        var logger = Mock.Of<ILogger<MyClass>>();

        var myClass = new MyClass(logger);

        var message = "a message";

        // Act
        myClass.MyMethod(message);

        //Assert
        Mock.Get(logger)
            .Verify(l => l.Log(LogLevel.Error,
                    It.IsAny<EventId>(),
                    It.Is<It.IsAnyType>((o, t) => ((IReadOnlyList<KeyValuePair<string, object>>) o).Last().Value.ToString().Equals(message)),
                    It.IsAny<Exception>(),
                    (Func<It.IsAnyType, Exception, string>) It.IsAny<object>()),
                Times.Once);
    }
}

I tried to do similar thing in my code by nsubstitute, but it's failed, as (Arg.Is<-object->) does not equal It.Is<It.IsAnyType> in moq.

           _logger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);

            _logger.Received().Log(
                Arg.Any<LogLevel>(),
                Arg.Any<EventId>(),
                Arg.Is<object>(o => o.ToString().Contains("bad")),
                null,
                Arg.Any<Func<object, Exception, string>>());
AdvancingEnemy
  • 382
  • 3
  • 20

1 Answers1

0

A potential workaround is to fetch the call information and process it manually. For example:

// Assuming this object contains the expected key-value pairs that are logged:
var expectedLogState = new List<KeyValuePair<string, object>>();

loggerMock.ReceivedCalls().Should().NotBeEmpty();
var logInput = loggerMock.ReceivedCalls().First().GetArguments();
logInput[0].Should().Be(LogLevel.Error);
(logInput[2] as IEnumerable<KeyValuePair<string, object>>).Should().Contain(expectedLogState);
Pooven
  • 1,744
  • 1
  • 25
  • 44