Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to mock NLog log methods?

Tags:

nlog

Is it possible/easy to mock NLog log methods, using Rhino Mocks or similar?

like image 317
cbp Avatar asked Feb 07 '11 05:02

cbp


2 Answers

Using Nuget : install-package NLog.Interface

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

like image 166
Tim S Avatar answered Oct 06 '22 01:10

Tim S


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));
like image 37
Piotr Perak Avatar answered Oct 06 '22 02:10

Piotr Perak