2017-06-28 36 views
0

我有一個單元測試某個邏輯的參數化測試。有幾個測試用例由NUnit TestCaseAttribute捕獲。在NUnit中如何添加一個測試與另一個測試的所有參數一起運行?

現在我想利用完全相同的參數來測試一個稍微不同的邏輯。

我意識到我可以通過不同的屬性傳遞參數 - TestCaseSourceAttribute並使用相同的來源進行多個單元測試。

但我想知道是否可以使用TestCaseAttribute(我發現在這個特定的測試中更方便)並重新使用參數進行另一個測試?

我的解決方案包括反射:

[TestCase(Impl.SqlErrorCode.PartiallyDocumentedColumn, 1978.14, "MyTable", ChangeTypeCode.AddTable, "dbo.MyAuxTable:MyTableId")] 
[TestCase(Impl.SqlErrorCode.UndocumentedColumn, 1978.15, "MyAuxTable", ChangeTypeCode.AddTable, "dbo.MyAuxTable:MyAuxTableId")] 
[TestCase(Impl.SqlErrorCode.UndocumentedColumn, 1978.16, "MyTable", ChangeTypeCode.AddTable, "dbo.MyTable:MyAuxTableId")] 
[TestCase(Impl.SqlErrorCode.NonExistingColumnInComments, 1969.19, "MyTable", ChangeTypeCode.None, "dbo.MyTable:Remarks")] 
public async Task AddTableWithBadComments(Impl.SqlErrorCode expectedSqlErrorCode, decimal step, string tableName, int sqlErrorState, string expectedObjectName) 
{ 
    // ... 
} 

private static IEnumerable GetParametersOfAnotherTest(string testName) 
{ 
    var testCaseAttrs = typeof(IntegrationTests).GetMethod(testName).GetCustomAttributes<TestCaseAttribute>(); 
    return testCaseAttrs.Select(a => a.Arguments); 
} 

[TestCaseSource(nameof(GetParametersOfAnotherTest), new object[] { nameof(AddTableWithBadComments) })] 
public async Task AddTableWithBadCommentsNoVerify(Impl.SqlErrorCode expectedSqlErrorCode, double _step, string tableName, int sqlErrorState, string expectedObjectName) 
{ 
    // A different logic, but with the same parameters. 
} 

它有一些問題,但。

所以,我的問題是這樣的 - 是否有NUnit方式來運行測試方法Y與測試方法X的參數,其中後者使用TestCaseAttribute來提供參數?

我使用nunit 3.7.1

回答

1

實際答案很短。 NUnit重用參數的方式是TestCaseSourceAttribute。 :-)

我想我會解釋爲什麼你的解決方案無法正常工作。

在NUnit 3+中,TestCaseTestCaseSource等屬性不僅僅是數據的容器。它們實現了NUnit調用的接口,以使屬性在特定的測試上運行。

您的代碼正在處理TestCaseAttribute就好像它不過是參數的數據存儲一樣。但是這個屬性實際上做了一些事情,其中​​一些與TestCaseSourceAttribute不一樣。

從你的代碼中,我可以看到你自己想出了一部分。您的第一個方法依賴於將double轉換爲decimal的屬性,而第二個方法將該參數作爲double。這種差異當然是由於你不能有一個屬性的小數參數。

不幸的是,對於一個完整的解決方案,您將不得不復制或考慮兩個屬性之間的其他差異,這些全都歸因於C#在屬性參數上的限制。國際海事組織,這是不值得的。創建TestCaseData項的靜態數組並將它們用於這兩種方法是很簡單的。如果你讓自己的方法有效(這是可能的),那麼它的聰明纔是有利的。 :-)

相關問題