Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / C#
Tip/Trick

Changing App.Config on the fly for unit testing

Rate me:
Please Sign up or sign in to vote.
4.33/5 (4 votes)
10 Jun 2011CPOL1 min read 33.3K   5   1
Changing App.Config on the fly for unit testing
First of all, a short description and the problem which I've faced. Our team has a list of unit tests that are more likely to integration tests. These tests before starting deploy database make some changes in the current environment and after running drop database and return environment back to its initial state. Of course, all configuration such as database connection strings and other we put to App.Config. Each of us runs these tests on a local machine using ReSharper and everything was fine until we had decided to run tests on build-machine sing standard "nunit-console" application. We created a standalone NUnit solution where we put all references on all test projects. When we tried to run tests on build-machine, we found out that all NUnits have requirement that app.confing should have the same name as as NUnit project + . config, i.e., we had to unite our dozens of app.configs in one.

Our solution is to change app.config before each test will be run.

Here is the code example to do it:

[SetUp]
public void SetUp()
{
    ServiceTestEnvironment.SetAssemblyConfig(GetType().Assembly)
}


SetUp of NUnit framework guarantees that method marked with this attribute will be invoked before any test. So we change app.config before running tests.

Here is the implementation of SetAssemblyConfig:
public static void SetAssemblyConfig(Assembly assembly)
{
	Configuration currentConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
	Configuration assemblyConfiguration = ConfigurationManager.OpenExeConfiguration(new Uri(assembly.CodeBase).LocalPath);
	if (assemblyConfiguration.HasFile && string.Compare(assemblyConfiguration.FilePath, currentConfiguration.FilePath, true) != 0)
	{
	assemblyConfiguration.SaveAs(currentConfiguration.FilePath);
				ConfigurationManager.RefreshSection("appSettings");
	ConfigurationManager.RefreshSection("connectionStrings");	
	}
}


I've posted this tip because I couldn't find anything about this topic. Hope it can help somebody and saves time on debugging and tracing unit tests.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
Generaluseful Pin
Shahriar Iqbal Chowdhury/Galib9-Jun-11 10:16
professionalShahriar Iqbal Chowdhury/Galib9-Jun-11 10:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.