Gotchas: MSTest AppDomain changes in VS 2008

Friday, January 4, 2008 – 4:17 PM

Here’s something we at p&p ran into the other day while moving some of our unit tests from Visual Studio 2005 to 2008. This was actually on the EntLib forum and a bug logged by the community against the issue with the MSTest team. Unfortunately it didn’t get fixed but represents a nasty trap for the unwary.

Consider the following test, which is a distillation of what might happen if you had a test which called a class that we using the AppDomain base directory to find some other resource – a configuration file for example:

  public class AppDomainFixture 
     public void TestAppDomainLoading() 
         string value = AppDomain.CurrentDomain.BaseDirectory; 
         Assert.AreEqual<string>(Environment.CurrentDirectory, value); 

In VS 2005 this would pass. The AppDomain base directory would be set to the current directory which would be MSTest’s working directory containing your test and application DLLs. Not so in VS 2008! You get the following error:

Failed TestAppDomainLoading TestAppDomain Assert.AreEqual failed. Expected:<C:\trunk\TestAppDomain\TestResults\adem_REMISSION 2008-01-04 16_05_08\Out>. Actual:<C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\>.    

MSTest has set the AppDomain base directory to the VS Common7\IDE\ directory thus breaking your tests.

How to fix it

Luckily there is a workaround… You can set the base directory value before starting the test using your test class’ constructor or test setup method.

  public AppDomainFixture() 

This fixed most of the issues we were having with our tests.

A lesson Learnt?

Of course if our code has mocked out the file system and environment then this problem would have been even simpler to fix and we would have further decoupled our classes. Now that a file system mock is available there’s no reason not to do this!

Technorati Tags: ,,

  1. 7 Responses to “Gotchas: MSTest AppDomain changes in VS 2008”

  2. Holy cow!

    Thanks a bunch. I was about to go insane…

    By Mike on Feb 27, 2008

  3. Thanks for the tip, I had bumped into this problem and didn’t realize how to fix it yet.

    By Simone Busoli on Feb 29, 2008

  4. Thanks a million. I was going to be doing some hacking (i.e. “programming by coincidence”) to fix this problem, but knowing the root cause of this problem is much better!

    By Dave on May 8, 2008

  5. Much thanks, I had figured out that the base directory for the app domain was different but didn’t know how to change it. You saved me another day’s work.

    By Damian Edwards on Jun 18, 2008

  6. Seems to be fixed in VS2008 SP1

    By riezebosch on Jan 12, 2009

  1. 2 Trackback(s)

  2. Feb 25, 2008: Upgrading CAB solution to Visual Studio 2008 and making all the tests pass « ICoder
  3. Jul 6, 2011: How do I do Dependency Injection in a test project (TFS 2008) using Castle - Programmers Goodies

Sorry, comments for this entry are closed at this time.