Unit testing programmatic web.config edits

Perhaps there's some easier way with VSTS's testing, but because I know not everyone has that, I'm trying to write unit tests for the programmatic manipulation of web.config data.

So on one hand, you've got...

System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.

in your configuration editing junk. Works like a champ when you call Save() on that object. The problem is that HttpRuntime.AppDomainAppVirtualPath has no value in a unit test. The weird thing though is that you can call the above code from the test and call it's Save() and it throws no errors. It sure thinks it's saving some config data somewhere, but I can't figure out where.

I know I'm being nutty here, but I really want to be able to test this stuff. Any suggestions?

EDIT: Actually, the test is manipulating web.config in the C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG folder. That's odd.


  • In the interest of getting things done, I setup a test site in my solution and use that with VSTS tests. I still don't like the interface.

  • did you ever find a way to get HttpRuntime.AppDomainAppVirtualPath returning a value? i'm having a similiar problem with some vendor software.

  • I know it's been a long time since you posted this, but, anyways, I was having this exactly same issue, and figured out a solution.

    The "problem" in a unit test is you don't have a HttpContext, so I changed my code a bit:

    Configuration config = HttpContext.Current != null
    ? WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath)
    : ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    In this case, when you run your test, HttpContext will be null, and the code will look for App.Config in your test project.

    Sorry for bad english, hope this can help someone.

  • Sweet this was just what I was looking for. Such a shame more of this wasn't TDD ready from the outset.

  • @Diego, thanks for posting this. I tried HostingEnvironment.ApplicationVirtualPath and it worked.

Comments have been disabled for this content.