Friday, August 31, 2012

Using log4net MemoryAppender for unit testing

Sometimes unit testing existing code can be really hard. Especially when coding by exceptions (using Try.. Catch.. then do nothing!).

This will look a bit like this



From the outside we might not be able to test whether ReallyDoSomething has thrown an exception except if we can validate state changes done by ReallyDoSomething. And if we can't change the code much (like adding dependencies using parameters or change the return type of the method) we won't be able to write that test at all.

Another way is to use the logger to validate that.

The piece of code above use Log4Net as the logging framework and allow us to use it in our unit tests like this



Just like that we can intercept all the logged messages by our production code.

I've used this trick a few times now when other options were not available. Hope it helps.

2 comments:

darichkid said...

This is even better than log4net:
http://www.kellermansoftware.com/p-14-net-logging-library.aspx

Simon Laroche said...

T'es un king Pascal