Hi,
I am using JustMock for some app.config settings:
Mock.Arrange(() => ConfigurationManager.AppSettings["MyAppSettingKey1"]).Returns("MyAppSettingValue1");
Mock.Arrange(() => ConfigurationManager.AppSettings["MyAppSettingKey2"]).Returns("MyAppSettingValue2");
Mock.Arrange(() => ConfigurationManager.AppSettings["MyAppSettingKey3"]).Returns("MyAppSettingValue3");
However, if I do this, other values that are not explicitly mocked are not available:
var myValue = ConfigurationManager.AppSettings["MyAppSettingKeyNotMocked"])
throws a System.NullReferenceException
Is there a better way to mock Configuration.AppSettings?
4 Answers, 1 is accepted
You're mocking more than you need. Try this:
var appSettings = ConfigurationManager.AppSettings;
Mock.Arrange(() => appSettings[
"MyAppSettingKey1"
]).Returns(
"MyAppSettingValue1"
);
Mock.Arrange(() => appSettings[
"MyAppSettingKey2"
]).Returns(
"MyAppSettingValue2"
);
Mock.Arrange(() => appSettings[
"MyAppSettingKey3"
]).Returns(
"MyAppSettingValue3"
);
Regards,
Stefan
Telerik

Hi Stefan,
thank you for your reply. This does indeed work and solves my problem perfectly. I don't fully understand your solution though.
I fail to see the difference between:
Mock.Arrange(() => ConfigurationManager.AppSettings["MyAppSettingKey1"]).Returns("MyAppSettingValue1");
and
var appSettings = ConfigurationManager.AppSettings;
Mock.Arrange(() => appSettings["MyAppSettingKey1"]).Returns("MyAppSettingValue1");
Why does this retain the original behaviour for unarranged keys when my initial version doesn't? I realise you are mocking the instance, but not of my subsequent code refers to this new variable directly.
This expression:
Mock.Arrange(() => ConfigurationManager.AppSettings[
"MyAppSettingKey1"
])
When you take out the property access outside the arrangement expression:
var appSettings = ConfigurationManager.AppSettings;
Mock.Arrange(() => appSettings[
"MyAppSettingKey1"
])
Regards,
Stefan
Telerik

Hi Stefan,
thank you very much for a really clear explanation. I now completely understand.
Thanks again.