I have created a class library MultipleConfigFiles
, which has a method getConfigData
. This method reads data from config files.
public class Class1
{
public string getConfigData()
{
string configData = ConfigurationManager.AppSettings["key"].ToString();
return configData;
}
}
Now I have a console application ConsoleAppConfig
, in which I have given the reference of the class library.In the main method, I have created a object for the library class and called the method.
static void Main(string[] args)
{
Class1 c = new Class1();
string data = c.getConfigData();
Console.Write(data);
}
This console application has 2 different config files dev.config
and prod.config
. In the main App.config file , I have used configSource to map the appropriate config file.
<appSettings configSource="dev.config" />
Dev.config file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<add key="key" value="dev" />
</appSettings>
Till here it is working fine.That is, when I run the console app, the method returns dev
.
Now,I have created a MSTest project for this class library.
public class Class1Tests
{
[TestMethod()]
public void getConfigDataTest()
{
Class1 obj = new Class1();
var result = obj.getConfigData();
}
}
Now the problem is, when I run this test, it throws an error saying
"An exception of type 'System.NullReferenceException' occurred in MultipleConfigFiles.dll but was not handled in user code.
Additional information: Object reference not set to an instance of an object."
Since the config files are in ConsoleApplication , the method is not able to read the appsetting variables from there. Is there any way I can maintain the configuration files globally so that both of them use individually , or is there any better way to handle this.
Any inputs are appreciated.Thanks.