How To Unit Test That A Log4Net Error Has Been Made

When you test your code you want to test two things.  That the successful route and the unsuccessful route through your method works as expected.  One way of doing this is to write a unit test that checks that Log4Net has written a message.  Luckily, the code for this is pretty easy  If you want to learn how to write this test, read on.

Unit Test Log4net Call

When you use Log4Net in your project, in most cases you'll have a declaration at the top of your class, like this:

        private readonly ILog _log = LogManager.GetLogger(typeof(MyClass));

As it's not injected into the constructor, you may think it will be hard to test. Luckily, Log4Net has made this easy using the MemoryAppender class found within the log4net.Appender.MemoryAppender. Let's say you have this method:

        public void MethodToTest()

            catch(Exception ex)
                _log.Error("An error has occurred");

You could write this test:

        public void MyTest()
            var appender = new log4net.Appender.MemoryAppender();

            var result = _sut.MethodToTest();

            var logEntries = appender.GetEvents();

Create a new MemoryAppender before we run the test. After the test, call the GetEvents() method. In here you will find a list of all the message Log4Net has written... simples!

submit to reddit

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

Back to top