Unit Testing log4net Logging Code

January 20th 2014 Logging Unit Testing

There's usually no need to unit test the logging code. If you just want to ignore it in your tests, there's nothing you need to do when using log4net. The emitted information will not be logged anywhere by default. For production use you will of course configure the appenders in the .config file as required.

What if you still want to make sure you're going to log the right information? It turns out you can use unit tests for this. The key to it is configuring an appender directly from your unit test code. The best candidate for it is MemoryAppender. Here's the required code:

var appender = new MemoryAppender();
BasicConfigurator.Configure(appender);

Make sure you keep a reference to the appender. You'll need it at the end of the test to check the logged information:

var logEntries = appender.GetEvents();

The call will return an array of LoggingEvents which you can then inspect using asserts, making sure the correct number of events was logged and that each one of them contains expected data.

You're probably not going to use this often, but it can come in handy when you need it.

Get notified when a new blog post is published (usually every Friday):

Copyright
Creative Commons License