BeniaminoBaggins
BeniaminoBaggins

Reputation: 12433

Mock of Microsoft.Extensions.Logging.ILogger is null after instantiation

I'm trying to mock Microsoft.Extensions.Logging.ILogger but it ends up being null in the [TestInitialise] method below. How come it is null?

public class MockLogger : ILogger
{
    // Define a public property for the message. 
    // Your unit tests can query this property
    // to validate that the method was called. 

    public IDisposable BeginScope<TState>(TState state)
    {
        throw new NotImplementedException();
    }

    public bool IsEnabled(LogLevel logLevel)
    {
        throw new NotImplementedException();
    }

    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
    {
        throw new NotImplementedException();
    }

    public void LogToOperations(string message)
    {
    }
}


[TestClass]
public class DataServiceTests
{


    private ILogger<DataService> _logger;

    [TestInitialize]
    public void TestInitialize()
    {
        _logger = new MockLogger() as ILogger<DataService>;

    }

Upvotes: 0

Views: 992

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236188

Your logger does not implement generic ILogger<T> interface. That's why as operator returns null when conversion between MockLogger and ILogger<DataService> is not possible.

NOTE: Usually mocking types which you don't own considered as a bad practice. And one more thing - your MockLogger class is not mock - it's a Dummy. For mocking I would suggest you some existing library. E.g. NSubstitute or Moq. With NSubstitute:

_logger = Substitute.For<ILogger<DataService>>;

without any additional code.

Upvotes: 3

Related Questions