Home > General > Creating new application domains while running a unit test

Creating new application domains while running a unit test

While using MSTest to test some code that creates new application domains, I kept running into an exception while using both Visual Studio’s test runner and ReSharper’s test runner. This code works under normal circumstances, but fails to run during the execution of a unit test.

[TestMethod]
public void Test1()
{
    AppDomain domain = AppDomain.CreateDomain("Test");
    domain.DoCallBack(() => Console.WriteLine("Hello world"));
}

Line 5 would throw the following exception:

Test method TestProject.DemoTest.Test1 threw exception: 
System.IO.FileNotFoundException: Could not load file or assembly 'TestProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

After some trial and error, I discovered the newly created application domain uses a different application base.

AppDomain domain = AppDomain.CreateDomain("Test");

Console.WriteLine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase);
Console.WriteLine(domain.SetupInformation.ApplicationBase);

Running the code above during the execution of a normal application (ie console application) will print out the same location. In my case, it would be "D:\projects\DemoCode\bin\Debug". But when this code is executed in the context of a test runner, the newly created application domain will print "C:\Program Files (x86)\JetBrains\ReSharper\v6.1\Bin\" while using ReSharper’s test runner or "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\" while using Visual Studio’s test runner.

To make sure both application domains use the same application base, I had to modify how I created new application domains.

AppDomain domain = AppDomain.CreateDomain(
	"Test",
	new Evidence(AppDomain.CurrentDomain.Evidence),
	new AppDomainSetup
	{
		ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
	});
  1. July 25, 2014 at 5:42 pm

    Your style is realkly unique compared to other people I have read stuf from.
    I appreciate yoou for posting when you’ve got the
    opportunity, Guess I’ll just bookmark this web site.

  2. good inventory
    September 3, 2014 at 2:28 pm

    Aw, this was an extremely good post. Finding the time and actual
    effort to make a top notch article… but what can I say… I put things
    off a lot and don’t seem to get anything done.

  1. No trackbacks yet.

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: