Skip to content

Instantly share code, notes, and snippets.

@pmunin
Created March 22, 2016 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmunin/db8a2386dd610f665b45 to your computer and use it in GitHub Desktop.
Save pmunin/db8a2386dd610f665b45 to your computer and use it in GitHub Desktop.
.NET Tests .config loader
using System;
using System.Configuration;
using System.Linq;
using System.Reflection;
namespace {MyProject}_Tests
{
public abstract class ConfigFileContext : IDisposable
{
public static ConfigFileContext Change(string path)
{
return new ChangeConfigFileContext(path);
}
public abstract void Dispose();
private class ChangeConfigFileContext : ConfigFileContext
{
private readonly string oldConfig =
AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE").ToString();
private bool disposedValue;
public ChangeConfigFileContext(string path)
{
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", path);
ResetConfigMechanism();
}
public override void Dispose()
{
if (!disposedValue)
{
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", oldConfig);
ResetConfigMechanism();
disposedValue = true;
}
GC.SuppressFinalize(this);
}
private static void ResetConfigMechanism()
{
typeof(ConfigurationManager)
.GetField("s_initState", BindingFlags.NonPublic |
BindingFlags.Static)
.SetValue(null, 0);
typeof(ConfigurationManager)
.GetField("s_configSystem", BindingFlags.NonPublic |
BindingFlags.Static)
.SetValue(null, null);
typeof(ConfigurationManager)
.Assembly.GetTypes()
.Where(x => x.FullName ==
"System.Configuration.ClientConfigPaths")
.First()
.GetField("s_current", BindingFlags.NonPublic |
BindingFlags.Static)
.SetValue(null, null);
}
}
}
}
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace {MyProject}_Tests
{
[TestClass]
public class ConfigFileContextInitializer
{
static ConfigFileContext config;
[AssemblyInitialize]
public static void AssemblyInitialize(TestContext ctx)
{
config = ConfigFileContext.Change(@"..\..\..\{MyProject}\web.config");
DatabaseConfig.Initialize();
}
[AssemblyCleanup]
public static void AssemblyCleanup()
{
if (config != null)
config.Dispose();
}
}
}
@pmunin
Copy link
Author

pmunin commented Mar 22, 2016

  • Replace {MyProject} with your main project namespace
  • Put these two files in test project
  • Replace "{MyProject}\web.config" with valid path to config file (web.config or app.config)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment