Config files and NUnit tests
A comment left on my last post about TestDriven.NET asked how to tell NUnit to use an application configuration file.
This is easy, just have a configuration file with the same name as your test assembly + ".config" sitting next to your assembly and NUnit automatically picks it up. This is NUnit's built-in behavior and has nothing to do with TestDriven.NET, so it works for any way you invoke NUnit such as NUnit GUI, NUnit console, or TestDriven.NET.
So if you have a test assembly named "MyUnitTests.dll", just have a post build step that takes a config file and copies it to the output folder making sure it is named "MyUnitTests.dll.config".
The simplest way to do this using VS.NET is to add a post build event to your project that does something like this:
copy /Y "$(ProjectDir)app.config" "$(TargetPath).config"
Path Substitution
Sometimes config files have to contain fully-qualified paths to other files. (Preferably they are relative paths, but we've run into some strange cases where they needed to be fully qualified...don't ask). For example:
<configuration>
<appSettings>
<add key="path.to.some.file"
value="C:\Some\Fully\Qualified\Path\SomeFile.xml"/>
</appSettings>
</configuration>
When test are run from different locations (developer 1 works on his C: drive, developer 2 works on his D: drive, the build server builds under a dated build directory etc...) It may be necessary to get a little fancier with this post build step and actually do text replacement step to fix up the paths to represent the current build location.
There are lots of ways to solve this, but one way is to change the post build event to call a batch file which in turn calls a vbscript that does a text replacement something like this:
Post Build Event:
"$(ProjectDir)\PostBuild.cmd" "$(ProjectDir)" "$(TargetPath)"
--app.config--
<configuration>
<appSettings>
<add key="path.to.some.file"
value="{PATHPLACEHOLDER}\SomeFile.xml"/>
</appSettings>
</configuration>
--PostBuild.cmd--
copy /Y "%1app.config" "%2.config"
cscript.exe //nologo "%1strrepl.vbs" "%2.config" "{PATHPLACEHOLDER}" "%1"
--strrepl.vbs--
Option Explicit
Dim oFSO, oFile, strFilename, strData, strPattern, strReplace
Const ForReading = 1
Const ForWriting = 2
If (WScript.Arguments.Count <> 3) Then
WScript.Echo "Usage: strrepl %filename% %searchstring% %replacestring%"
WScript.Quit
End If
strFileName = WScript.Arguments(0)
strPattern = WScript.Arguments(1)
strReplace = WScript.Arguments(2)
' Get File
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFile = oFSO.OpenTextFile(strFileName, ForReading)
strData = oFile.ReadAll
oFile.Close
strData = Replace(strData, strPattern, strReplace)
' Write File
Set oFile = oFSO.OpenTextFile(strFileName, ForWriting)
oFile.Write strData
oFile.Close