0

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 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.

jonsca
  • 10,218
  • 26
  • 54
  • 62
user450354
  • 11
  • 2
  • Which version of Moles are you using? Is it v0.94.51023.0 by chance? There are issues with that build and the ConfigurationManager. Have you tried using v0.94.51006.1? – Matt Jun 30 '11 at 16:29
  • Thanks Matt, I am indeed using 0.94.51023.0. I have tried to get 51006.1 so I can see if the issue exists in that version, but can't find a download anywhere. I have now managed to narrow my problem down to static constructors. Moles is correctly mocking ConfigurationManager in instance members, but when ConfigurationManager is called from a static constructor, Moles is not mocking it correctly. I have posted a separate thread for this issue at: http://stackoverflow.com/questions/6015173/how-use-moles-for-a-constructor – user450354 Jul 01 '11 at 09:09

1 Answers1

0
  1. make a copy of current app.settings section:

    NameValueCollection appSettings = new NameValueCollection(ConfigurationManager.AppSettings);
    
  2. 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");
    
  3. Create the delegate:

    MConfigurationManager.AppSettingsGet =
      () =>
      {
        return appSettings;
      };
    
tecfield
  • 203
  • 2
  • 11