Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Static Readonly log4net logger, any way to change logger in Unit Test?

My class has this line:

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

When I go to unit test, I can't inject a moq logger into this interface so I could count log calls.

Is there a way to do this? Log4net recommends static readonly pattern for loggers. What's best way to handle it?

like image 294
AberAber Avatar asked May 28 '13 16:05

AberAber


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.


2 Answers

You can use MemoryAppender instead a mocked logger. By this approach, you can configure log4net to collect the log events in memory and get them by GetEvents() to verify.

I found the these useful examples:

  • https://gist.github.com/plaurin/3563082#file-trycache-cs
  • http://jake.ginnivan.net/verifying-logged-messages-with-log4net/

Here is the first:

[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");
}

And the more detailed:

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();
    }
}
like image 146
Vereb Avatar answered Oct 14 '22 05:10

Vereb


While log4net recommends this pattern, nothing prevents you from instantiating the logger outside the class, and inject it. Most of the IoCs can be configured to inject one and the same instance. That way, for your unit tests you can inject a mock.

I would recommend a wrapper around LogManager.GetLogger, which returns always one and the same logger instance per type:

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());
        }
    }
} 
like image 43
Sunny Milenov Avatar answered Oct 14 '22 06:10

Sunny Milenov