Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a separate AppDomain for each xUnit.net test method?

Tags:

c#

.net

xunit.net

xUnit uses the same AppDomain for the whole test assembly, this is problematic as I'm testing a UI library and need to create a new Application instance for each individual test.

It works when I run a single test, but when I Run All the first test passed, but all subsequent tests fail with Cannot create more than one System.Windows.Application instance in the same AppDomain at the line where I create a new Application object.

like image 618
Flagbug Avatar asked Jan 20 '14 15:01

Flagbug


People also ask

Does xUnit create a new class for each test?

xUnit.net creates a new instance of the test class for every test that is run, so any code which is placed into the constructor of the test class will be run for every single test.

How do I run a parallel test in xUnit?

Set to true to run the test assemblies in parallel against one other; set to false to run them sequentially. The default value is false . Set to true to run the test collections in parallel against one other; set to false to run them sequentially. The default value is true .

How does an Appdomain get created?

AppDomains are created by the . Net runtime when a managed application is initialised. When you start ABC. EXE, it gets an application domain.

Which attribute is used to mark a method as test method in xUnit?

Testing a positive case This method is decorated with the Fact attribute, which tells xUnit that this is a test.


1 Answers

Perhaps you could try by making your test class like this:

public class DomainIsolatedTests : IDisposable
{
  private static int index = 0;
  private readonly AppDomain testDomain;

  public DomainIsolatedTests()
  {
    var name= string.Concat("TestDomain #", ++index);
    testDomain = AppDomain.CreateDomain(name, AppDomain.CurrentDomain.Evidence, AppDomain.CurrentDomain.SetupInformation);
    // Trace.WriteLine(string.Format("[{0}] Created.", testDomain.FriendlyName)); 
  }

  public void Dispose()
  {
    if (testDomain != null)
    {        
      // Trace.WriteLine(string.Format("[{0}] Unloading.", testDomain.FriendlyName));
      AppDomain.Unload(testDomain);        
    }
  }

  [Fact]
  public void Test1()
  {
    testDomain.DoCallBack(() => {
      var app = new System.Windows.Application();

      ...
      // assert
    });
  }

  [Fact]
  public void Test2()
  {
    testDomain.DoCallBack(() => { 
      var app = new System.Windows.Application();

      ...
      // assert
    });
  }

  [Fact]
  public void Test3()
  {
    testDomain.DoCallBack(() => {
      var app = new System.Windows.Application();

      ...
      // assert
    });
  }

  ...
}
like image 144
IronGeek Avatar answered Oct 12 '22 13:10

IronGeek