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

后端 未结 6 1293
我寻月下人不归
我寻月下人不归 2020-12-08 01:55

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         


        
6条回答
  •  北荒
    北荒 (楼主)
    2020-12-08 02:25

    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.

    
    
      
      
      
        
      
    
    

    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"];
    

提交回复
热议问题