這個想法讓我感興趣,所以我做了一點挖掘。 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