7
votes

We are writing unit tests for our business layer running under .NET 4.0. The business layer is a straightforward C# class library that usually runs within SOAP and REST web services. Our application uses log4net within a separate wrapper assembly for logging. The C# code in the logging assembly has an assembly info directive that tells log4net the name of the configuration file, a la-

[assembly: log4net.Config.XmlConfigurator(ConfigFile="AcmeLogging.config", Watch=true)]

Initializing the log4net through the wrapper works fine in the web services. When we initialize it from with our unit test assembly it does not appear to see the configuration file. The configuratino file is configured through properties to be copied to the execution directory, and we do see it in the bin\debug directory. A quick console test program using the logging assembly running from within that same folder works fine. The curious thing is that the behavior problems are intermittent, and pop up on different developers' machines at different times and cannot be cured in any deterministic way.

Stepping through the wrapper assembly code, the log4netLogManager.GetLogger() call appears to return correctly, but the list of appenders returned by log.Logger.Repository.GetAppenders() is empty. Since this incorrect behavior is the same whether the file is in the Bin\Debug folder or not, we believe that it is not seeing the file.

Any clues as to what we're missing about running log4net in the Microsoft Test Framework would be greatly appreciated.

1

1 Answers

8
votes

Unit tests are unique in the fact that if you need configuration files in your unit tests you need to include them as deployment items. Here is an example of how I do this within my test class:

[TestClass]
[DeploymentItem("hibernate.cfg.xml")]
public class AsyncForwardingAppenderTest
{

}

In addition to the Deployment attribute you need to Enable Deployment in your test settings. To do this go to Test->Edit Test Settings->. Then click on Deployment area on right. Click the checkbox Enable Deployment.

After doing this and running your test your config file should be located in your test results folder. TestResults\username_machine date stamp\Out. If your config file is not located in this folder it will not work. This is what the DeploymentItem attribute does. It sticks the file in this Out folder.

If you don't want to include the DeploymentItem attribute on every test class what I did was to create a base test class that all of the tests that use log4net inherit from and mark it with the DeploymentItem attribute.