如何在xUnit.net测试中仅运行一次安装代码

我正在尝试使用Xunit设置我的测试。 我要求删除测试文件夹开头的所有图像,然后每个方法都会调整一些图像大小,并将其输出的副本保存到文件夹中。 该文件夹只应清空一次,然后每个方法将自己的图像保存到该文件夹​​中。

当我使用IUseFixture ,在每次测试之前仍然会调用ClearVisualTestResultFolder函数,所以我最终只在文件夹中有一个图像。

 public class Fixture { public void Setup() { ImageHelperTest.ClearVisualTestResultFolder(); } } public class ImageHelperTest : IUseFixture { public void SetFixture(EngDev.Test.Fixture data) { data.Setup(); } public static void ClearVisualTestResultFolder() { // Logic to clear folder } } 

如果我将ClearVisualTestResultFolder放在构造函数中,那么每个测试方法也会调用一次。 我需要在执行所有测试方法之前运行一次,我该如何实现?

如果重要,我使用ReSharper测试运行器。

遵循此xUnit讨论主题中的指导,看起来您需要在Fixture上实现构造函数并实现IDisposable。 这是一个完整的示例,其行为符合您的要求:

 using System; using System.Diagnostics; using Xunit; using Xunit.Sdk; namespace xUnitSample { public class SomeFixture : IDisposable { public SomeFixture() { Console.WriteLine("SomeFixture ctor: This should only be run once"); } public void SomeMethod() { Console.WriteLine("SomeFixture::SomeMethod()"); } public void Dispose() { Console.WriteLine("SomeFixture: Disposing SomeFixture"); } } public class TestSample : IUseFixture, IDisposable { public void SetFixture(SomeFixture data) { Console.WriteLine("TestSample::SetFixture(): Calling SomeMethod"); data.SomeMethod(); } public TestSample() { Console.WriteLine("This should be run once before every test " + DateTime.Now.Ticks); } [Fact] public void Test1() { Console.WriteLine("This is test one."); } [Fact] public void Test2() { Console.WriteLine("This is test two."); } public void Dispose() { Console.WriteLine("Disposing"); } } } 

从控制台运行程序运行时,您将看到以下输出:

D:\ xUnit> xunit.console.clr4.exe test.dll / html foo.htm xUnit.net console test runner(64位.NET 4.0.30319.17929)版权所有(C)2007-11 Microsoft Corporation。

xunit.dll:版本1.9.1.1600测试程序集:test.dll

SomeFixture ctor:这应该只运行一次

测试完成:2中的2

SomeFixture:处理SomeFixture

共2次,0次失败,0次跳过,耗时0.686秒

然后,当您打开测试输出文件foo.htm时,您将看到其他测试输出。

xUnit.net v1.x中的旧IUseFixture接口已被两个新接口替换: IClassFixtureICollectionFixture 。 此外,将fixture值注入测试的机制已从属性设置器更改为构造函数参数。 类夹具创建一次并在同一类中的所有测试之间共享(很像旧的IUseFixture)。 除了在同一测试集合中的所有测试之间共享单个实例之外,集合装置的工作方式相同。

每次测试都会调用IUseFixture.SetFixture一次。 Fixture本身只创建一次。

换句话说,你不应该在你的SetFixture方法中做任何事情,但你应该在Fixture构造函数中触发它。

对于一次性清理,在Fixture上实现IDisposable.Dispose (尽管不是必需的)

请注意,在测试之间(甚至可能)共享状态是个坏主意。 最好使用像这样的TemporaryDirectoryFixture