MoqSection Configuration

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 set:

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

When the ConfigurationManager is injected into my application. So far, so good. Now I want to say that if they try to access Global.Settings.Transactions.TestStatus inside my modules, it returns true. Here I am embarrassed, and my initial attempts are simply dumped 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 zero error. I am simply immersed in ridicule and will be very grateful for the help. Thanks

+3
source share
1 answer

, . "" .

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

new CustomSection, , Get . CustomSection TransactionElement.

+4

Source: https://habr.com/ru/post/1779158/


All Articles