How to use web.config when unit testing an asp .net application

.Netasp.netUnit Testing

.Net Problem Overview


I am starting out with unit testing, I have a method that uses the web.config for a connection string.

I was hoping to be able to use

[DeploymentItem("web.config")]

to get the web config file, this still leaves me with null reference exceptions (that'd be what I write my next test for).

How do I use the config file included with the project I am trying to test?

I am using the testing framework included in VS 2008, if that makes any difference.

Thanks

.Net Solutions


Solution 1 - .Net

Unit test projects should have their own config file.

On a test project you can choose Add, New Item, Application Configuration File.

This file will behave exactly like a web.config, but then for your unit tests.

Solution 2 - .Net

You can load in a web.config or app.config from any location using OpenMappedExeConfiguration. Make sure System.Configuration is added to your project's References.

ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap()
fileMap.ExeConfigFilename = @"c:\my-web-app-location\web.config"

Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
string connectionString = config.AppSettings.Settings["ConnectionString"].Value;

Here is the web.config, pretty standard.

<?xml version="1.0"?>
<configuration>
  <configSections>
  </configSections>
  <appSettings>
    <add key="ConnectionString" value="Data Source=XXXX;Initial Catalog=XXX; Trusted_Connection=True;"/>
  </appSettings>
</configuration>

Update on 2017-09-29

I have come up a class to make it easier for reading AppSetitngs from file. I got the idea from Zp Bappi.

public interface IAppSettings
{
    string this[string key] { get; }
}

public class AppSettingsFromFile : IAppSettings
{
    readonly Configuration Config;

    public AppSettingsFromFile(string path)
    {
        var fileMap = new ExeConfigurationFileMap();
        fileMap.ExeConfigFilename = path;
        Config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
    }

    public string this[string key]
    {
        get
        {
            return Config.AppSettings.Settings[key].Value;
        }
    }
}

Here is how to use the class.

IAppSettings AppSettings = new AppSettingsFromFile(@"c:\my-web-app-location\web.confg");
string connectionString = AppSettings["ConnectionString"];

Solution 3 - .Net

Copy your web.config file into the "/bin" folder and rename it into "AppName.dll.config".

Where "AppName" - is the name of the resulting assembly.

I used this hack many times.

Solution 4 - .Net

You will want your results to be well-defined and repeatable. To to this, you'll need to be working against known data so that you can clearly define both your normal cases and your boundary cases. In my work, this is always a specific server and dataset so the Unit testing module has the connection string built in. Others prefer using a connection string out of the Unit Testing project. I've never seen anyone recommend the use of the web site's config file! (development or otherwise)

Solution 5 - .Net

I would recommend abstracting the configuration reading part, so that it could be mocked. Something like this, see Jon_Lindeheim's reply https://stackoverflow.com/questions/23513355/how-to-read-web-config-file-while-unit-test-case-debugging

Solution 6 - .Net

If you need a connection string, you are not writing a unit test (assuming that you are using the connection string for going to database). Unit tests are not supposed to interact with outside environment. You will want to run all of them after each check in so they better run at the speed of light.

For a unit test, you will want to isolate your code from your database. Modify your tests (and the code you are testing if necessary) so that you will not need to go to database for testing them.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionilivewithianView Question on Stackoverflow
Solution 1 - .NetGerrie SchenckView Answer on Stackoverflow
Solution 2 - .NetTonyView Answer on Stackoverflow
Solution 3 - .NetAlex from JitbitView Answer on Stackoverflow
Solution 4 - .NetMark BrittinghamView Answer on Stackoverflow
Solution 5 - .NetGokulnathView Answer on Stackoverflow
Solution 6 - .NetSerhat OzgelView Answer on Stackoverflow