Today I implemented the ConfigurationSection stuff in .NET you can use to interject your custom configuration structures into config files like web.config and app.config.  I wanted to test not only my implementation, but the classes that rely on the configuration but it wasn't exactly clear how I could get ConfigurationManager to load an arbitrary configuration.

The solution is quite simple and I figured it out after a bit of trial and error.  What got me was that I had a custom configuration file in a child directory of my unit test project("WebServices") and I had set the configuration file's build action to "Copy Always".  I had thought it would end up in "bin\Debug" but it correctly ended up in "bin\Debug\WebServices" so that's an important thing to keep in mind.

Outsmarting ConfigurationManager also requires that you have an accompanying file (empty text file works) that the configuration applies to.  So here's what the start of my [now working] test looks like:

    private static RequestHandlerSection _section;

    [TestFixtureSetUp]
    public void Setup()
    {
        using (var sw =
            File.CreateText(".\\WebServices\\RequestHandlerTests")
        )
        {
            sw.Close();
        }
        var config = ConfigurationManager.OpenExeConfiguration(
            ".\\WebServices\\RequestHandlerTests"
        );
        _section = (RequestHandlerSection)
            config.Sections[RequestHandlerSection.Name];
    }

    [Test]
    public void WorkDamnYouTest()
    {
        Assert.IsNotNull(_section);
        Assert.IsNotEmpty(_section.Security);
    }
}

Ideally at some point in the future ConfigurationManager could get a Load(string xml) or some such so we don't have to deal with this nonsense.  While I could add one with an extension method I'd like to see it get into the framework to improve unit testability.