【问题标题】:Reload app.config with nunit使用 nunit 重新加载 app.config
【发布时间】:2010-10-31 06:50:57
【问题描述】:

我有多个 NUnit 测试,我希望每个测试都使用特定的 app.config 文件。 有没有办法在每次测试之前将配置重置为新的配置文件?

【问题讨论】:

    标签: c# .net nunit app-config


    【解决方案1】:

    试试:

    /* Usage
     * using(AppConfig.Change("my.config")) {
     *   // do something...
     * }
     */
    public abstract class AppConfig : IDisposable
    {
        public static AppConfig Change(string path)
        {
            return new ChangeAppConfig(path);
        }
        public abstract void Dispose();
    
        private class ChangeAppConfig : AppConfig
        {
            private bool disposedValue = false;
            private string oldConfig = Conversions.ToString(AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE"));
    
            public ChangeAppConfig(string path)
            {
                AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", path);
                typeof(ConfigurationManager).GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, 0);
            }
    
            public override void Dispose()
            {
                if (!this.disposedValue)
                {
                    AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", this.oldConfig);
                typeof(ConfigurationManager).GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, 0);
                    this.disposedValue = true;
                }
                GC.SuppressFinalize(this);
            }
        }
    }
    

    【讨论】:

    • 这似乎很完美。你能解释一下它的实际作用吗? :-)
    • 这对我不起作用(使用 .NET 4.0)。我不得不扩展它,请在此处查看我的答案:stackoverflow.com/questions/6150644/…
    【解决方案2】:

    如果您的问题是您针对不同的测试用例集需要有不同的配置,您可以拥有不同的测试项目,每个项目都有一个配置文件。然后一次运行一个测试项目。

    【讨论】:

      【解决方案3】:

      answered a similar question 代表 Powershell。同样的技术在这里应该可以工作,只需在测试开始时调用以下代码:

      System.AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", configPath)

      编辑:实际上看起来这在已编译的 exe 中更复杂 - 您需要执行 something like this 才能重新加载配置。

      【讨论】:

        猜你喜欢
        • 2013-03-29
        • 2011-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-14
        • 2011-01-25
        • 1970-01-01
        • 2019-08-04
        相关资源
        最近更新 更多