据我所知,xUnit没有全局初始化/拆卸扩展点.然而,创建一个是很容易的.只需创建一个实现IDisposable
的基本测试类,并在构造函数中进行初始化,在IDisposable.Dispose
方法中进行拆卸.这看起来像这样:
public abstract class TestsBase : IDisposable
{
protected TestsBase()
{
// Do "global" initialization here; Called before every test method.
}
public void Dispose()
{
// Do "global" teardown here; Called after every test method.
}
}
public class DummyTests : TestsBase
{
// Add test methods
}
但是,每次调用都会执行基类设置和拆卸代码.这可能不是你想要的,因为它效率不高.更优化的版本将使用IClassFixture<T>
接口,以确保全局初始化/拆卸功能只调用一次.对于这个版本,您不会从测试类扩展基类,而是实现IClassFixture<T>
接口,其中T
表示fixture类:
using Xunit;
public class TestsFixture : IDisposable
{
public TestsFixture ()
{
// Do "global" initialization here; Only called once.
}
public void Dispose()
{
// Do "global" teardown here; Only called once.
}
}
public class DummyTests : IClassFixture<TestsFixture>
{
public DummyTests(TestsFixture data)
{
}
}
这会导致TestsFixture
的构造函数只运行一次