When you use the NUnit grapical interface to run unit tests, it short circuits the output from log4net. This happens because NUnit itself is using log4net, and by default it turns the log outputs off. The end result of this is that you go through all this trouble to get log4net working correctly, and your log entries mysteriously fail to show up when you run the unit tests. This affect both console logging, and logging to files.
The resolution:
There is definitely some information out there, but most of what I found was a touch cryptic. The purpose of this entry is share a plain English way of working around this problem.
Step 1: Add an application config file and rename it to something like "Test.config". Don't be hard headed like me and ask "Why do I need to rename this file". Just do it and make sure that the config file you add has the appropriate build action set so it gets copied to the bin directory as content.

Step 2: Add your log4net configuration entry to the "Test.config" file. If you're reading this article, you should already know how to do this. But if you don't, please refer to the log4net setup documentation.
Step 3: Add code to your unit test project to configure log4net at runtime (i.e. after the NUnit GUI has messed with the configuration). The code snippet below does it in the constructor of one of my test classes. This has the obviously limitation of only firing our configuration code once a test in this particular class is fired. Optional: If you want a more global version of this approach that applies to all of your tests classes, embed the runtime log4net configuration in a class marked as being a [SetupFixture] instead of placing in an actual test class.
public class LoggingTests
{
public LoggingTests()
{
FileInfo fileInfo = new FileInfo(@"C:\MOHQ\Middleware\UnitTests\bin\Debug\Test.config");
log4net.Config.XmlConfigurator.Configure(fileInfo);
}
[Test]
public void BasicLogTest()
{
log.Error("Hmm, Write my log entry already");
}
[Test]
public void DatabaseLogTest()
{
}
At this point your done. Any log4net entries you have configured should now show up in the appropriate logs.
< Prev | Next > |
---|