11

我的课有这行:

private static readonly ILog log = LogManager.GetLogger(typeof(Prim));

当我进行单元测试时,我无法将 moq 记录器注入此接口,因此我可以计算日志调用。

有没有办法做到这一点?Log4net 建议记录器使用静态只读模式。处理它的最佳方法是什么?

4

3 回答 3

11

虽然 log4net 推荐这种模式,但没有什么能阻止您在类外实例化记录器并注入它。大多数 IoC 可以配置为注入同一个实例。这样,对于您的单元测试,您可以注入一个模拟。

我会推荐一个围绕 LogManager.GetLogger 的包装器,它总是为每种类型返回一个相同的记录器实例:

namespace StackOverflowExample.Moq
{
    public interface ILogCreator
    {
        ILog GetTypeLogger<T>() where T : class;
    }

    public class LogCreator : ILogCreator
    {
        private static readonly IDictionary<Type, ILog> loggers = new Dictionary<Type, ILog>();
        private static readonly object lockObject;

        public ILog GetTypeLogger<T>() where T : class
        {
            var loggerType = typeof (T);
            if (loggers.ContainsKey(loggerType))
            {
                return loggers[typeof (T)];
            }

            lock (lockObject)
            {
                if (loggers.ContainsKey(loggerType))
                {
                    return loggers[typeof(T)];
                }
                var logger = LogManager.GetLogger(loggerType);
                loggers[loggerType] = logger;
                return logger;
            }
        }
    }

    public class ClassWithLogger
    {
        private readonly ILog logger;
        public ClassWithLogger(ILogCreator logCreator)
        {
            logger = logCreator.GetTypeLogger<ClassWithLogger>();
        }

        public void DoSomething()
        {
            logger.Debug("called");
        }
    }

    [TestFixture]
    public class Log4Net
    {
        [Test]
        public void DoSomething_should_write_in_debug_logger()
        {
            //arrange
            var logger = new Mock<ILog>();
            var loggerCreator = Mock.Of<ILogCreator>(
                c =>
                c.GetTypeLogger<ClassWithLogger>() == logger.Object);

            var sut = new ClassWithLogger(loggerCreator);

            //act
            sut.DoSomething();

            //assert
            logger.Verify(l=>l.Debug("called"), Times.Once());
        }
    }
} 
于 2013-05-28T19:38:07.113 回答
2

您可以改用MemoryAppender模拟记录器。通过这种方法,您可以配置 log4net 以收集内存中的日志事件并通过GetEvents()验证。

我发现了这些有用的例子:

这是第一个:

[SetUp]
public void SetUp()
{
    this.memoryAppender = new MemoryAppender();
    BasicConfigurator.Configure(this.memoryAppender);

    ...
}

[Test]
public void TestSomething()
{
    ...

    // Assert
    Assert.IsFalse(
        this.memoryAppender.GetEvents().Any(le => le.Level == Level.Error),
        "Did not expect any error messages in the logs");
}

更详细的:

public static class Log4NetTestHelper
{
    public static string[] RecordLog(Action action)
    {
        if (!LogManager.GetRepository().Configured)
            BasicConfigurator.Configure();
        var logMessages = new List<string>();
        var root = ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root;
        var attachable = root as IAppenderAttachable;

        var appender = new MemoryAppender();
        if (attachable != null)
            attachable.AddAppender(appender);

        try
        {           
            action();
        }
        finally
        {
            var loggingEvents = appender.GetEvents();
            foreach (var loggingEvent in loggingEvents)
            {
                var stringWriter = new StringWriter();
                loggingEvent.WriteRenderedMessage(stringWriter);
                logMessages.Add(string.Format("{0} - {1} | {2}", loggingEvent.Level.DisplayName, loggingEvent.LoggerName, stringWriter.ToString()));
            }
            if (attachable != null)
                attachable.RemoveAppender(appender);
        }

        return logMessages.ToArray();
    }
}
于 2017-10-11T14:55:29.077 回答
2

只要readonly拿走,Logger 就可以像通常的接口对象一样工作。

请参阅以下正在测试的简单示例:

using System;
using log4net;

namespace StackOverflowExample.Moq
{
    public class ClassWithLogger
    {
        private static ILog _log;
        //private static readonly ILog log = LogManager.GetLogger(typeof(Prim));

    public ClassWithLogger(ILog log)
    {
        _log = log;
    }

        public void DoSomething(object para = null)
        {
            try
            {
                if(para != null)
                {
                    _log.Debug("called");
                }
                else
                {
                    throw new System.ArgumentException("Parameter cannot be null");
                }
            }
            catch (Exception ex)
            {
                _log.Fatal("Exception raised!", ex);
            }
        }
    }
} 

单元测试代码:

[TestMethod]
public void Test_DoSomething_logger()
{
    //arrange
    var mockLog = new Mock<log4net.ILog>();
    var classWithLogger = new ClassWithLogger(mockLog.Object);
    mockLog.Setup(m => m.Debug(It.IsAny<string>()));
    mockLog.Setup(m => m.Fatal(It.IsAny<string>(), It.IsAny<Exception>()));

    //act1
    classWithLogger.DoSomething(new object());

    //assert1
    mockLog.Verify(l => l.Debug("called"), Times.Once());

    //act2
    classWithLogger.DoSomething();

    //assert2
    mockLog.Verify(x => x.Fatal("Exception raised!", It.IsAny<Exception>()));
}

和主程序调用:

public void MainProgramCall()
{
    //......
    ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    var classWithLogger = new ClassWithLogger(log);

    classWithLogger.DoSomething(new object());

    //......

    classWithLogger.DoSomething();

    //......
}
于 2018-09-13T11:40:06.090 回答