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
yes we can run asp.net application without web. config file,if u r not configure any settings in web. config file then it will take machine. config file for default configurtaons.
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.
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"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With