I am looking for a way to 'detour' a single item in a configuration file with Moles. I can do this:
NameValueCollection appsettings = new NameValueCollection();
appSettings.Add("MyKey", "MyValue");
System.Configuration.Moles.MConfigurationManager.AppSettingsGet = () => this.appSettings;
This works fine, however the class which I am trying to test uses some other开发者_C百科 configuration settings including ConfigSections and the Moles detour seems to have broken this. I only want to replace a specific value, not the whole section. In TypeMock, I could do this:
Isolate.WhenCalled(() => ConfigurationManager.AppSettings["MyKey"]).WithExactArguments().WillReturn("MyValue");
When I mock the configurationManager using TypeMock, my test passes, but when I use the Moles version (which looks like it should do the same thing) it fails meaning that Moles must be affecting the ConfigurationManager class in a way which TypeMock doesn't.
Any help on how I can use moles to just behave in the way which TypeMock does would be greatly appreciated.
make a copy of current app.settings section:
NameValueCollection appSettings = new NameValueCollection(ConfigurationManager.AppSettings);
Modify the part you need by calling Set/Add function (keep in mind that 'Add' function does not overwrite existing values but it adds a new value for the key. On the other hand, 'Set' always creates a new entry and gets rid of the existing values):
appSettings.Set("key name", "new value");
Create the delegate:
MConfigurationManager.AppSettingsGet = () => { return appSettings; };
精彩评论