A site devoted to discussing techniques that promote quality and ethical practices in software development.

Sunday, November 14, 2010

Beware when using AppDomain.BaseDirectory in NUnit

In my previous post I accused Uri() exhibiting some quirky behavior,
The reason is that depending on whether the base uri for file protocol is your current execution directory, that constructor will drop the last component of your base uri if the current directory is not your base uri  when forming the final uri.
This is indeed a wrong accusation. System.Uri() is functioning correctly in accordance to RFC 3986. For example
Assert.IsTrue( (new Uri( new Uri(@"C:\A\B\C"), "test.txt")).LocalPath,
               @"C:\A\B\test.txt" );
Assert.IsTrue( (new Uri( new Uri(@"C:\A\B\C\"), "test.txt")).LocalPath,
               @"C:\A\B\C\test.txt" );

In normal application, like a console application or WinForm application, the following result is true:
Debug.Assert( AppDomain.CurrentDomain.BaseDirectory.EndWith( @"\" ) );

But when executing the above statement in a TestFixture class in NUnit, the assert fails. This is because when NUnit defines the AppDomainSetup.ApplicationBase, it fails to include a trailing '\'. NUnit simply uses Environment.CurrentDirectory, which does not have a ending '\'. Incidentally, the sample code makes the mistake of assuming the Environment.CurrentDirectory ends with a '\' resulting in forming an incorrect path to the application configuration file.

Normally, this discrepancy does not matter if you use System.IO.Path.Combine() to form path names. However, in the case of when log4net is used inside NUnit it becomes an issue when it uses Uri( Uri, string ) to form the Uri to the log4net configuration file with the value from AppDomain.CurrentDomain.BaseDirectory. The end result is a wrong Uri to the configuration file. To overcome this problem in NUnit, it is therefore wise to specify a full path name for the configuration file in the NUnit's project's configuration file as recommended.

After all these experiments, I am none the wiser what is the official convention for AppDomain.BaseDirectory and Environment.CurrentDirectory? At least in Uri, it is unambiguously defined in the RFC. Perhaps someone reading this from Microsoft can care to comment on this to let the world know if there is such a convention at all.

1 comment:

Charlie said...

Just stumbled across this post. I'll fix it in NUnit so there's always a slash at the end of the ApplicationBase.

Charlie

Blog Archive