How To Read UnitTest Project's App.Config From Test With HostType(“Moles”)

后端 未结 6 1445
夕颜
夕颜 2021-02-13 23:02

I have the folowing tests:

[TestClass]
public class GeneralTest
{
    [TestMethod]
    public void VerifyAppDomainHasConfigurationSettings()
    {
        string         


        
6条回答
  •  执笔经年
    2021-02-13 23:40

        [ClassInitialize]
        public static void MyClassInitialize(TestContext testContext)
        {
            System.Configuration.Moles.MConfigurationManager.GetSectionString =
                (string configurationName) =>
                    {
                        ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
                        Assembly assembly = Assembly.GetExecutingAssembly();
                        fileMap.ExeConfigFilename = assembly.Location + ".config";
                        Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
                        object section = config.GetSection(configurationName);
                        if (section is DefaultSection)
                        {
                            ConfigurationSection configurationSection = (ConfigurationSection) section;
                            Type sectionType = Type.GetType(configurationSection.SectionInformation.Type);
                            if (sectionType != null)
                            {
                                IConfigurationSectionHandler sectionHandler =
                                    (IConfigurationSectionHandler)AppDomain.CurrentDomain.CreateInstanceAndUnwrap(sectionType.Assembly.FullName, sectionType.FullName);
                                section = 
                                    sectionHandler.Create(
                                        configurationSection.SectionInformation.GetParentSection(), 
                                        null,
                                        XElement.Parse(configurationSection.SectionInformation.GetRawXml()).ToXmlNode());
                            }
                        }
    
                        return section;
                    };
        }
    

提交回复
热议问题