NUnit and application configuration files.
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).
Leave a Reply