Using memory appender to test logger

I found a bug in IglooCoder.Commons, the Logger doesn’t log the correct class. The fix is easy, but I want to create a test before fixing it, in case the next release the problem came back.

How to test the logger without logging at the log files generated? This is the perfect situation we should use memory appender.

  [TestFixture]
    public class LogTests
    {
        private MemoryAppender _appender;
        private LoggingEvent _event;

        [TestFixtureSetUp]
        public void Init()
        {
            Log.Initialize(new AglcLog4NetLogger(SystemInfo.ApplicationBaseDirectory + "\\Log4Net.config"));
            _appender = new MemoryAppender();

            _appender.Name = "Unit Testing Appender";

            _appender.Layout =
                new PatternLayout("%date{dd-MM-yyyy HH:mm:ss,fff} %5level [%2thread] %message (%logger{1}:%line)%n");

            _appender.Threshold = Level.All;

            _appender.ActivateOptions();

            Logger root = ((Hierarchy) LogManager.GetRepository()).Root;

            root.AddAppender(_appender);

            root.Repository.Configured = true;
        }

        [Test]
        public void should_get_the_correct_class_name_to_log()
        {
            _appender.Clear();
            Log.For(this).Info("testing");

            _event = _appender.GetEvents()[0];

            var data = _event.GetLoggingEventData();

            Assert.AreEqual(this.GetType().ToString(), data.LoggerName);
        }
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s