Mocking application settings

By Mirek on (tags: mocking, settings, testing, categories: code)

Last time I showed a simple way of using application settings in our wpf application. This time I would like to present you my way of testing Properties.Settings, or rather mocking it in our application tests.

First of all we need to make our application code independent of the concrete implementation of auto generated Settings class. Let’s define an interface which will contains the same properties that are defined in our Settings.

   1: public interface ISettingsService
   2: {      
   3:     string MyUserSetting { get; set; }
   4:  
   5:     string MyApplicationSetting { get; }
   6:  
   7:     void Reload();
   8:  
   9:     void Save();
  10: }

We have one user scope setting and one application scope setting. Their names must match the ones defined in our application settings. Additionally we have two methods. One for reloading settings and one for saving changed settings to config file. Both methods are implemented in ApplicationSettingsBase.
Now since the Settings class is auto generated, we cannot make it implementing our settings interface.

   1: public sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
   2: ...

But fortunately it is also partial which gives us a possibility to add a new class with the same name and make any modification on that class

   1: public partial class Settings : ISettingsService
   2: {
   3: }

Important note about partial classes: they must have the same name and be placed in the same assembly and same namespace. Having that in place we can now make our application code use the ISettingsService instead of concrete Settings class.

   1: ISettingsService appSettings = Settings.Default;
   2: //.. do stuff with your app settings

There is only one inconvenience with this approach. Whenever you change, add or delete setting you will need to update the ISettingsService interface.

Now it is quite easy to mock our settings. I use Moq which makes it even simpler here.

   1: var settingsMock = new Mock<ISettingsService>();
   2: settingsMock.SetupAllProperties();
   3: ISettingsService appSettings = settingsMock.Object;
   4: //...do stuff with your appSettings

That’s it.