Testing logging using Log4Net and NUnit

I’ve been playing around with log4net and scratch my head trying to figure out how to test my loggings. This might seem like a strange thing to want to do, but else would you make sure you track errors you handle gracefully in your application. Also I’ve seen some cases where the logging was actually failing and nobody noticed until we went live. The solution i came up with goes something like this.
A sample sais more that a thousand words…
using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Core;
using log4net.Layout;
using NUnit.Framework;

namespace ModelTest
{
    [TestFixture]
    public class TestLogging
    {
        MemoryAppender memoryAppender;

        [TestFixtureSetUp]
        public void TestFixtureSetUp()
        {
            var consoleAppender = new ConsoleAppender() 
                { Name = "Console", Layout = new PatternLayout("%d [%t] %-5p %m%n") };

            memoryAppender = new MemoryAppender() 
                { Name = "Test2", Threshold = Level.Warn};

            var forwardingAppender = new ForwardingAppender();
            forwardingAppender.AddAppender(consoleAppender);
            forwardingAppender.AddAppender(memoryAppender);

            BasicConfigurator.Configure(forwardingAppender);
        }

        [Test]
        public void GivenALog_WhenLogging_ThenLogsAreWritten()
        {
            //Given
            memoryAppender.Clear();
            
            //When
            methodToTest();

            //Then
            var events = memoryAppender.GetEvents();
            Assert.That(events.Length,Is.EqualTo(3));
        }

        private void methodToTest()
        {
            var log = LogManager.GetLogger("Some Logger");
            log.Info("info");
            log.Debug("debug");
            log.Warn("warn");
            log.Error("error");
            log.Fatal("fatal");
        }
    }
}


Please note that my assert is only for demo purposes, you can’t count on the number of logs since other elements in your code might also log things.

No comments:

Post a Comment