这个想法让我感兴趣,所以我做了一点挖掘。 NUnit不具备开箱即用的功能,但NUnit提供了一个完整的可扩展性框架。我发现this great article about extending NUnit - 这是一个很好的起点。玩过它之后,我想出了以下解决方案:如果夹具中的某个测试失败,则将调用装有自定义CleanupOnError
属性的方法。
这里的测试看起来像:
[TestFixture]
public class NUnitAddinTest
{
[CleanupOnError]
public static void CleanupOnError()
{
Console.WriteLine("There was an error, cleaning up...");
// perform cleanup logic
}
[Test]
public void Test1_this_test_passes()
{
Console.WriteLine("Hello from Test1");
}
[Test]
public void Test2_this_test_fails()
{
throw new Exception("Test2 failed");
}
[Test]
public void Test3_this_test_passes()
{
Console.WriteLine("Hello from Test3");
}
}
其中属性很简单:
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class CleanupOnErrorAttribute : Attribute
{
}
这里是它是如何从外接程序执行:
public void RunFinished(TestResult result)
{
if (result.IsFailure)
{
if (_CurrentFixture != null)
{
MethodInfo[] methods = Reflect.GetMethodsWithAttribute(_CurrentFixture.FixtureType,
CleanupAttributeFullName, false);
if (methods == null || methods.Length == 0)
{
return;
}
Reflect.InvokeMethod(methods[0], _CurrentFixture);
}
}
}
但这里的棘手的部分:插件必须放在NUnit亚军旁边的addins
目录中。 Mine被放置在TestDriven的NUnit runner旁边。NET目录:
C:\Program Files\TestDriven.NET 2.0\NUnit\addins
(我创建了addins
目录,它是不存在)
编辑另一件事是清理方法必须static
!
我砍了一个简单的插件,你可以从my SkyDrive下载源代码。您必须在适当的位置添加对nunit.framework.dll
,nunit.core.dll
和nunit.core.interfaces.dll
的引用。
一些注意事项:属性类可以放在代码中的任何位置。我不想将它放在与插件本身相同的程序集中,因为它引用了两个Core
NUnit程序集,所以我将它放在了不同的程序集中。如果您决定将其放在其他地方,请记住要更改CleanAddin.cs
中的行。
希望有所帮助。
如果您不想在每次测试中进行清理,或者每次测试后都不会进行清理。抱歉。 – rein 2009-07-15 14:47:09