我正在尝试使用Xunit设置我的测试。我要求删除测试文件夹开头的所有图像,然后每个方法都会调整一些图像大小,并将其输出的副本保存到文件夹中。该文件夹只应清空一次,然后每个方法将自己的图像保存到文件夹中。
当我使用IUseFixture<T>
时,在每次测试之前仍然会调用ClearVisualTestResultFolder
函数,因此我最终只会在文件夹中显示一个图像。
public class Fixture
{
public void Setup()
{
ImageHelperTest.ClearVisualTestResultFolder();
}
}
public class ImageHelperTest : IUseFixture<EngDev.Test.Fixture>
{
public void SetFixture(EngDev.Test.Fixture data)
{
data.Setup();
}
public static void ClearVisualTestResultFolder()
{
// Logic to clear folder
}
}
如果我将ClearVisualTestResultFolder
放在构造函数中,那么每个测试方法也会调用一次{{1}}。我需要在执行所有测试方法之前运行一次,我该如何实现呢?
如果重要,我使用ReSharper测试运行器。
答案 0 :(得分:30)
遵循此xUnit discussion topic中的指导,看起来您需要在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<SomeFixture>, 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&gt; xunit.console.clr4.exe test.dll / html foo.htm xUnit.net 控制台测试运行器(64位.NET 4.0.30319.17929)版权所有(C) 2007-11微软公司。
xunit.dll:版本1.9.1.1600测试程序集:test.dll
SomeFixture ctor:这应该只运行一次
测试完成:2 of 2
SomeFixture:Disposing SomeFixture
总共2次,0次失败,0次跳过,耗时0.686秒
然后,当你打开测试输出文件foo.htm时,你会看到另一个测试输出。
答案 1 :(得分:6)
IUseFixture<T>.SetFixture
一次。 Fixture本身只创建一次。
换句话说,你不应该在你的SetFixture方法中做任何事情,但你应该在Fixture构造函数中触发它。
对于一次性清理,在Fixture上实现IDisposable.Dispose
(虽然不是必需的)
请注意,在测试之间(甚至可能)共享状态是一个坏主意。最好使用TemporaryDirectoryFixture
like this one。