nfplee
nfplee

Reputation: 7977

Moq ConfigurationSection

my application has the following code:

public interface IConfigurationManager {
    CustomSection Settings { get; }
}

public class ConfigurationManager : IConfigurationManager {
    public CustomSection Settings { get { return (CustomSection)WebConfigurationManager.GetSection("customSettings"); } }
}

public class CustomSection : ConfigurationSection {
    [ConfigurationProperty("transactions", IsRequired = true)]
    public TransactionsElement Transactions {
        get { return (TransactionsElement)base["transactions"]; }
    }
}

public class TransactionsElement : ConfigurationElement {
    [ConfigurationProperty("testStatus", DefaultValue = true)]
    public bool TestStatus {
        get { return (bool)base["testStatus"]; }
        set { base["testStatus"] = value; }
    }
}

Now in my Global.asax.cs file i have the following static variable defined:

public static CustomSection Settings = ServiceLocator.Current.GetInstance<IConfigurationManager>().Settings;

Where ConfigurationManager is injected in my application. So far so good. Now what i want to say is if they try to access Global.Settings.Transactions.TestStatus inside my unit tests it returns true. This is where i get confused and my initial attemps have just been thrown together. So far i have (Edited):

var cm = new Mock<IConfigurationManager>();
var cs = new Mock<CustomSection>();
var te = new Mock<TransactionsElement>();

cm.SetupGet(m => m.Settings).Returns(cs.Object);
cs.SetupGet(s => s.Transactions).Returns(te.Object);
te.SetupGet(e => e.TestStatus).Returns(true);

But when i try to access Global.Settings.Transactions.TestStatus it throws a null error. I'm just diving into mocking and would really appreciate the help. Thanks

Upvotes: 3

Views: 5147

Answers (1)

Phill
Phill

Reputation: 18796

Because you're returning a new object, not a mocked object. You can't 'Setup' a non-proxied object.

configurationManager.Setup(c => c.Settings).Returns(new CustomSection());

The new CustomSection, needs to be a mocked object in order for you to setup a Get on the property. So you need to mock CustomSection and TransactionElement.

Upvotes: 4

Related Questions