Question

I have a settings provider which is untestable (corporate legacy code). I'm trying to wrap the settings provider in a Settings Repository to reduce the amount of untestable code. So instead of having 20 methods using the Settings provider, we will instead have 1. The rest implement the SettingsRepository interface.

I'm having trouble making the tests afterwards though, which usually indicates i did something wrong.

I'm hoping you can help find out what.

    public class SettingsRepository : ISettingsRepository
{
    public SettingsRepository() {Settings = Settings.Default; }
    public Settings Settings { get; set; }
}

public interface ISettingsRepository
{
    Settings Settings { get; set; }
}

I use unity to inject the repository. The way i get something out of the repository is as follows:

_settingsRepository.Settings.SecureCache

So here's the problem. I can mock/stub the SettingsRepository interface using nsubstitute but what i need to do is actually mock "Settings" to setup a return for SecureCache.

Is there a way to "deep mock" in nsubstitute so i can do something like:

_settingsRepository.Settings.SecureCache.Returns("www.somepath.com");

Currently "settings" is null and i don't have anything i can mock there.

My fallback solution is to add all the setting fields directly on the SettingsRepository but i would love to avoid that since it will just move untestable code elsewhere in the solution.

Was it helpful?

Solution

Using NSubstitue (version 1.5.0.0 )you can do as below. You can create an instance of Settings (or you can even create a fake instance), then return the fake SecureCache as below.

 public class SettingsRepository : ISettingsRepository {
    public SettingsRepository() { Settings = Settings.Default; }
    public Settings Settings { get; set; }
}

public interface ISettingsRepository {
    Settings Settings { get; set; }
}

public class Settings {
    public Settings Default { get; set; }
    public string SecureCache { get; set; }
}

[TestFixture]
public class TestClass
{
    [Test]
    public void Subject_Scenario_Expectation()
    {
        var repoStub = Substitute.For<ISettingsRepository>();
        repoStub.Settings.Returns(new Settings() { SecureCache = "www.somepath.com" });

        Assert.IsNotNull(repoStub.Settings);
        Assert.IsNotNull(repoStub.Settings.SecureCache);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top