【发布时间】:2010-10-31 06:50:57
【问题描述】:
我有多个 NUnit 测试,我希望每个测试都使用特定的 app.config 文件。 有没有办法在每次测试之前将配置重置为新的配置文件?
【问题讨论】:
标签: c# .net nunit app-config
我有多个 NUnit 测试,我希望每个测试都使用特定的 app.config 文件。 有没有办法在每次测试之前将配置重置为新的配置文件?
【问题讨论】:
标签: c# .net 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);
}
}
}
【讨论】:
如果您的问题是您针对不同的测试用例集需要有不同的配置,您可以拥有不同的测试项目,每个项目都有一个配置文件。然后一次运行一个测试项目。
【讨论】:
我 answered a similar question 代表 Powershell。同样的技术在这里应该可以工作,只需在测试开始时调用以下代码:
System.AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", configPath)
编辑:实际上看起来这在已编译的 exe 中更复杂 - 您需要执行 something like this 才能重新加载配置。
【讨论】: