Is it possible to mock NLog log methods?

Using Nuget : install-package NLog.Interface

Then: ILogger logger = new LoggerAdapter([logger-from-NLog]);


You can only mock virtual methods. But if You create some interface for logging and then implement it using NLog You can use dependency injection and in Your tests use mocked interface to see if system under test (SUT) is logging what You expect it to log.

public class SUT
{
  private readonly ILogger logger;
  SUT(ILogger logger) { this.logger = logger;}
  MethodUnderTest() {
    // ...
    logger.LogSomething();
    // ...
  }
}

// and in tests
var mockLogger = new MockLogger();
var sut = new SUT(mockLogger);
sut.MethodUnderTest();
Assert.That("Expected log message", Is.Equal.To(mockLogger.LastLoggedMessage));

Tags:

Nlog