Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 477
Luke Puplett Avatar asked Jul 11 '14 07:07

Luke Puplett


People also ask

Where do I put log4net in web config?

Add log4net in config file config and enter the following details. Add a class Log. cs in the Utilities folder. Now, in the constructor of this class, instantiate logs for monitoring and debugger loggers.


1 Answers

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.

like image 95
Luke Puplett Avatar answered Sep 20 '22 12:09

Luke Puplett