Accessing Web.config directly in ASP.NET MVC 1

Posted by Neil T. on Stack Overflow See other posts from Stack Overflow or by Neil T.
Published on 2010-04-21T17:33:43Z Indexed on 2010/04/21 17:53 UTC
Read the original article Hit count: 237

I'm trying to implement integration testing in my ASP.NET MVC 1.0 solution. The technologies in use are LINQ-to-SQL, NUnit and WatiN. I recently discovered a pattern that will allow me to create a testing version of the database on the fly without modifying the development version of the database. I needed this behavior in order to run my user interface tests in WatiN that may modify the database. The plan is to modify the connection string in the Web.config file, and pass that new connection string to the DataContext constructor. This way, I don't have to add routes or modify my URLs in order to perform the integration testing.

I've set up the project so that the test setup can modify the connection string to point to the test database when the tests are running. The connection string is stored in web.config. The problem I'm having is that when I try to run the tests, I get a NullReferenceException when trying to access the HTTPContext. From everything that I have read so far, the HTTPContext is only available within the context of a controller. Here is the code for the property that is supposed to give me the reference to the Web.config file:

private System.Configuration.Configuration WebConfig
{
    get
    {
        ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();

        // NullReferenceException occurs on this line.
        fileMap.ExeConfigFilename = HttpContext.Current.Server.MapPath("~\\web.config");

        System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

        return config;
    }
}

Is there something that I am missing in order to make this work? Is there a better way to accomplish what I'm trying to achieve?

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about integration-testing