如何为每个xUnit.net测试方法使用单独的AppDomain?

Fla*_*bug 16 .net c# xunit.net

xUnit AppDomain对整个测试程序集使用相同的,这是有问题的,因为我正在测试UI库并需要Application为每个单独的测试创建一个新实例.

它在我运行单个测试时有效,但是当我Run All第一次测试通过时,所有后续测试都Cannot create more than one System.Windows.Application instance in the same AppDomain在我创建新Application对象的行中失败.

Iro*_*eek 6

也许您可以尝试通过这样的测试class:

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
    });
  }

  ...
}
Run Code Online (Sandbox Code Playgroud)

  • 嗯,这"工作",但问题是即使测试在DoCallBack方法中失败,xUnit也会报告测试成功.似乎异常被某种方式吞噬了 (2认同)