When writing unit tests you ideally want to test two paths, the successful route and the unsuccessful route. These two tests should give you confidence that your method works as expected. If you are using LogNet then in the unhappy path, it is likely that a log file is created. One way of testing an unhappy path then is to check that Log4Net has written a message as expected. Luckily, the code for writing this type of test is pretty easy. If you want to learn how to write this test, read on.

How To Unit Test Log4net Calls

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

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

You could write this test:

In the code above on Line4, we create a new MemoryAppender before we run the test. After the test, on Line9, the GetEvents() method is called to get the log stream. The stream will contain a list of all the message Log4Net has written... simples! YOu now have an easy way to test your sad paths. Happy Coding 🤘