MSTest - How do I initialize log4net for a UnitTest project?

Luke Puplett picture Luke Puplett · Jul 11, 2014 · Viewed 9.2k times · Source

I have a Visual Studio unit test project for testing an ASP.NET MVC project.

Adding the assembly-level log4net.Config.XmlConfigurator attribute to AssemblyInfo.cs doesn't work and other people on SO have found they have to use a direct call to log4net.Config.XmlConfigurator.Configure();

The question is, how can this be done for a unit test? The answer to use Microsoft.VisualStudio.TestTools.UnitTesting.AssemblyInitialize attribute on a class method doesn't work.

For me, this code results in an InvalidOperationException logged in the output window and the test session bombs early.

[TestClass]
public sealed class Startup
{
    [AssemblyInitialize]
    public void Configure()
    {
        System.Diagnostics.Debug.Write("Microsoft.VisualStudio.TestTools.UnitTesting.AssemblyInitialize");
    }
}

Reading the documentation, MSDN says not to use AssemblyInitialize on test projects for ASP.NET since they may be called more than once.

So how can this be done so that log4net is configured before any tests are run?

Answer

Luke Puplett picture Luke Puplett · Jul 11, 2014

The answer was that I was mis-using AssemblyInitialize.

Once I'd set the debugger to halt on first chance exceptions I was able to read that my method was not static and I'd not added a parameter accepting a TestContext to it.

A pretty crappy use of an attribute if the method has to be a certain way, if you ask me. Not very discoverable.

Anyway, this works:

[TestClass]
public static class Startup
{
    [AssemblyInitialize]
    public static void Configure(TestContext tc)
    {
        log4net.Config.XmlConfigurator.Configure();
    }
}

Regarding the advice not to use this for ASP.NET test, sod it. It might get run more than once but that doesn't matter.