S h o r t S t o r i e s

// Tales from software development

NUnit and application configuration files.

leave a comment »

When running unit tests your code isn’t going to be loading configuration values from the configuration file normally used. The config file used is always located in the same folder as the executable and has the same name as the entry executable but with ‘.config’ appended.

So when running your unit tests, what’s the filename and location of the config file your code is going to use ?

If you Google this you’ll find various answers depending on which version of NUnit you’re using, whether you’re running the tests using the GUI test runner or the console test runner, etc.

My test fixture setup copies the application’s config file to the location and filename that NUnit will use. I tried hardcoding the target filename but after trying the various suggested filenames without success I realised that there’s a much better approach: let the .NET framework tell us what the path of the file its using is.

The AppDomain.CurrentDomain.SetupInformation.ConfigurationFile property provides the path of the configuration file that is being used. So, the test fixture setup code needs to copy the project’s config file to this path:

string nunitConfig = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
string appConfig = Path.GetFileName(Assembly.GetExecutingAssembly().Location) + ".config";
File.Copy(appConfig, this.nunitConfig, true);

 
One thing to watch out for though – don’t try specifying a fully qualified path for the application configuration file using the executing assembly’s location. The problem is that NUnit runs your code in a separate AppDomain from a copy of your assembly in temporary folder. Although NUnit copies your assembly to the temporary folder it doesn’t copy the config file. However, the current working directory is set to the folder where the target assembly resides (e.g. MyProject\bin\debug) so the config file can be referenced using an unqualified path (i.e. just the filename).

Advertisements

Written by Sea Monkey

January 22, 2010 at 8:00 am

Posted in Development

Tagged with

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: