如何使用 HostType(“Moles”) 从测试中读取 UnitTest 项目的 App.Config

发布于 2024-09-30 17:53:22 字数 698 浏览 1 评论 0原文

我有以下测试:

[TestClass]
public class GeneralTest
{
    [TestMethod]
    public void VerifyAppDomainHasConfigurationSettings()
    {
        string value = ConfigurationManager.AppSettings["TestValue"];
        Assert.IsFalse(String.IsNullOrEmpty(value), "No App.Config found.");
    }

    [TestMethod]
    [HostType("Moles")]
    public void VerifyAppDomainHasConfigurationSettingsMoles()
    {
        string value = ConfigurationManager.AppSettings["TestValue"];
        Assert.IsFalse(String.IsNullOrEmpty(value), "No App.Config found.");
    }
}

它们之间的唯一区别是[HostType("Moles")]。但第一次通过了,第二次失败了。如何从第二个测试中读取 App.config?

或者我可以在其他地方添加另一个配置文件?

I have the folowing tests:

[TestClass]
public class GeneralTest
{
    [TestMethod]
    public void VerifyAppDomainHasConfigurationSettings()
    {
        string value = ConfigurationManager.AppSettings["TestValue"];
        Assert.IsFalse(String.IsNullOrEmpty(value), "No App.Config found.");
    }

    [TestMethod]
    [HostType("Moles")]
    public void VerifyAppDomainHasConfigurationSettingsMoles()
    {
        string value = ConfigurationManager.AppSettings["TestValue"];
        Assert.IsFalse(String.IsNullOrEmpty(value), "No App.Config found.");
    }
}

The only difference between them is [HostType("Moles")]. But the first passes and the second fails. How can I read App.config from the second test?

Or may be I can add some another config file in other place?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

摘星┃星的人 2024-10-07 17:53:22

假设您正在尝试访问 appSettings 中的值,那么在测试开始时添加配置怎么样?类似于:

ConfigurationManager.AppSettings["Key"] = "Value";

然后,当您的测试尝试读取 AppSettings“Key”时,将返回“Value”。

Assuming you are trying to access values in appSettings, how about just adding the configuration at the beginning of your test. Something like:

ConfigurationManager.AppSettings["Key"] = "Value";

Then when your test tries to read the AppSettings "Key", "Value" will be returned.

带刺的爱情 2024-10-07 17:53:22

您只需将“App.Config”文件添加到单元测试项目中即可。它会自动读取。

You just add your "App.Config" file to the unit test project . It will read automatically.

绝不服输 2024-10-07 17:53:22

请参阅 http://social.msdn。 microsoft.com/Forums/en/pex/thread/9b4b9ec5-582c-41e8-8b9c-1bb9457ba3f6

同时,作为解决方法,您可以尝试将配置设置添加到 Microsoft.Moles.VsHost.x86 .exe配置文件

See http://social.msdn.microsoft.com/Forums/en/pex/thread/9b4b9ec5-582c-41e8-8b9c-1bb9457ba3f6

In the mean time, as a work around, you could try adding the configuration settings to Microsoft.Moles.VsHost.x86.exe.config

捂风挽笑 2024-10-07 17:53:22
    [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;
                };
    }
    [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;
                };
    }
街角迷惘 2024-10-07 17:53:22

我在工作中遇到了这个问题,但不喜欢这些答案。我还遇到一个问题,即在静态构造函数中读取配置文件,这意味着在执行静态构造函数之前我无法 Mole ConfigurationManager 。

我在我的家用计算机上尝试了这个,发现配置文件被正确读取。原来我在家使用的是 Pex 0.94.51006.1。这比现在的稍微旧一些。我找到了旧学术版本的下载:
http://research.microsoft.com /en-us/downloads/d2279651-851f-4d7a-bf05-16fd7eb26559/default.aspx

我将其安装在我的工作计算机上,一切正常。此时,我将降级到旧版本,直到发布新的工作版本。

I ran across this issue at work and didn't like any of these answers. I also have the problem that the configuration file is being read in a static constructor which means I can't Mole ConfigurationManager before the static constructor is executed.

I tried this on my home computer and found that the configuration file was being read correctly. It turns out I was using Pex 0.94.51006.1 at home. This is slightly older than the current one. I was able to find a download for the older academic version:
http://research.microsoft.com/en-us/downloads/d2279651-851f-4d7a-bf05-16fd7eb26559/default.aspx

I installed this on my work computer and everything is working perfectly. At this point, I'm downgrading to the older version until a newer working version is released.

满栀 2024-10-07 17:53:22

这就是我用来获取正确的 AppConfig 和 ConnectionString 部分的方法:

var config = System.Configuration.ConfigurationManager.OpenExeConfiguration(Reflection.Assembly.GetExecutingAssembly().Location);

typeof(Configuration.ConfigurationElementCollection).GetField("bReadOnly", Reflection.BindingFlags.Instance | Reflection.BindingFlags.NonPublic).SetValue(System.Configuration.ConfigurationManager.ConnectionStrings, false);
foreach (Configuration.ConnectionStringSettings conn in config.ConnectionStrings.ConnectionStrings)
    System.Configuration.ConfigurationManager.ConnectionStrings.Add(conn);

foreach (Configuration.KeyValueConfigurationElement conf in config.AppSettings.Settings)
    System.Configuration.ConfigurationManager.AppSettings(conf.Key) = conf.Value;

此处看到 ConnectionString 部分

This is what I am using to get the correct AppConfig and ConnectionString sections:

var config = System.Configuration.ConfigurationManager.OpenExeConfiguration(Reflection.Assembly.GetExecutingAssembly().Location);

typeof(Configuration.ConfigurationElementCollection).GetField("bReadOnly", Reflection.BindingFlags.Instance | Reflection.BindingFlags.NonPublic).SetValue(System.Configuration.ConfigurationManager.ConnectionStrings, false);
foreach (Configuration.ConnectionStringSettings conn in config.ConnectionStrings.ConnectionStrings)
    System.Configuration.ConfigurationManager.ConnectionStrings.Add(conn);

foreach (Configuration.KeyValueConfigurationElement conf in config.AppSettings.Settings)
    System.Configuration.ConfigurationManager.AppSettings(conf.Key) = conf.Value;

Saw the ConnectionString part here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文