使用nunit重新加载app.config

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

尝试:

/* 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); } } } 

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

我为Powershell 回答了类似的问题 。 相同的技术应该在这里工作,只需在测试开始时调用以下内容:

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

编辑:实际上看起来这在编译的exe中更复杂 – 你需要做这样的事情才能重新加载配置。