Is it possible to mock NLog log methods?

拟墨画扇 提交于 2021-02-07 06:25:41

问题


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


回答1:


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));



回答2:


Using Nuget : install-package NLog.Interface

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




回答3:


The simple answer, is 'no'. Looking at the code, dependency-injection is not supported, which seems rather an oversight, especially as it doesn't look difficult to implement (at first glance).

The only interfaces in the project are there to support COM interop objects and a few other things. The main Logger concrete class neither implements an interface, nor provides virtual methods.

You could either provide an interface yourself, or use Moles/TypeMock/ another isolation framework to mock the dependency.



来源:https://stackoverflow.com/questions/4918440/is-it-possible-to-mock-nlog-log-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!