I tried to use ConfigurationManager for the first time so thats what I did:
1.) created a new Project (TestProject) 2.) rightclick on TestProject -> Add -> New Item -> Application Configuration File (Name: Conf.config) 3.) I edited the file so its looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="key1" value="output1"/>
<add key="key2" value="output2"/>
<add key="key3" value="output3"/>
</appSettings>
</configuration>
Now If I try to read the config my code is telling me that its empty :/
NameValueCollection appSettings = ConfigurationManager.AppSettings;
if (appSettings.Count == 0) //always true
Console.WriteLine("something is wrong");
Even if I try ConfigurationManager.AppSettings["key1"]
I dont get any output. Hm what am I doing wrong?
If you are doing testing, then try to mock your environment, instead of accessing configuration files, database, etc.
public interface IFooConfiguration
{
public string Key1 { get; }
public string Key2 { get; }
public string Key3 { get; }
}
Implement this interface like this:
public class FooConfiguration
{
public string Key1
{
get { return ConfigurationManager.AppSettings["key1"]; }
}
}
But for your testing, use mocked configuration (I used Moq for example):
Mock<IFooConfiguration> mock = new Mock<IFooConfiguration>();
mock.Setup(foo => foo.Key1).Returns("output1");
var sut = new Sut(mock.Object);
BTW application configuration file should have name App.config
.