Archive

Posts Tagged ‘Log4Net’

How to use Log4Net in Unittests

March 29th, 2009 raymondr 3 comments

Curious why you unittest don’t log any messages using Log4Net? And you do have the configuration set in your app.config file? This is propably the result because your log4net config file isn’t deployed in the TestResult directory.

To enable Log4Net in your MSTest unittests :

  • Add your Log4Net file to the deployment files
  • Read the Log4Net configuration in your Assembly Initialize method (see below)

Add The Log4Net file to the deployment files

  1. Double click on the LocalTestRun.testrunconfig File
  2. Select deployment items
  3. Click Add
  4. Browse to your Log4Net config file.
    (This can be the same file as in your web or Windows project. In this way you use the same configuration as in your normal project.)

Reading Log4Net configuration
You can read the Log4Net configuration in you class initialization method but then you will have to put this information in every unittest class in you assembly. A better way is to put this code in the AssemblyInitialize method. The AssemblyInitialize method is just like the ClassInitialize method but this method will be executed only once before the execution of the unittest in your assembly.

Create a new class, for example TestAssemblyInit.cs and add the code below

[AssemblyInitialize()]
public static void MyTestInitialize(TestContext testContext)
{
// Take care the log4net.config file is added to the deployment files of the testconfig
FileInfo fileInfo;
string fullPath = Path.Combine(System.Environment.CurrentDirectory, "log4net.config");
fileInfo = new FileInfo(fullPath);

// Reload the configuration
log4net.Config.XmlConfigurator.Configure(fileInfo);

// test to see if it works
Log.Info("check");
}

Categories: .Net, Dev, Uncategorized Tags: , ,