1

I am trying to use sitecore Fake DB for unit testing.

My custom config look like this

<sitecore>
<settings>
  <setting name="test1" value="value1" />
  <setting name="test2" value="value2" />
</settings>

Constants:

public static class Constants
{
    public constant string SettingsTest1 = "test1";
    public constant string SettingsTest2 = "test2";
}

Class:

Public class Implementation
{
 private static string _const1 = Sitecore.configuration.Settings.GetSetting(Constants.SettingsTest1);
 private static string _const2 = Sitecore.configuration.Settings.GetSetting(Constants.SettingsTest2);

 public string method()
 {
      var key = _const1;
      //Do something
 }
}

While writing unit tests, I am trying to use this to assign the value for settings - https://github.com/sergeyshushlyapin/Sitecore.FakeDb/wiki/Settings and when I write unit test for the method, the settings value is always null because it is trying to get the value from config file. How can I write unit test for the method to use the settings value from fake db instead of config file? Thanks!

2
  • I don't think so. I know I have to use Fake db but my question is how to write unit test for the method to use the value from Fake db for settings instead of the value from config file Commented Oct 4, 2017 at 8:32
  • 1
    I believe that your answer does indeed lie in the linked question. See @Zach's answer and demonstration of the SettingsSwitcher. sitecore.stackexchange.com/a/3006/73
    – Mark Cassidy
    Commented Oct 4, 2017 at 12:01

1 Answer 1

0

You should abstract the Sitecore.Configuration.Settings.GetSettings method. For example:

public interface IConfigurationSettings
{
    string GetSetting(string key);    
}

public class ConfigurationSettings : IConfigurationSettings
{
    public string GetSetting(string key)
    {
        return Sitecore.Configuration.Settings.GetSetting(key);
    }
}

When you have abstracted this you can inject the IConfigurationSettings and mock it in your unit test.

1

Not the answer you're looking for? Browse other questions tagged or ask your own question.