2011-08-18 85 views
4

我在visual studio 2010中有一個測試項目。我有一個TestMethod。在這裏面,我想遍歷一系列事物並測試每個事物。所以,我有1個測試,並且想要斷言N次(列表中的每個項目都是一次)。Visual Studio 2010單元測試 - 斷言失敗後繼續TestMethod的任何方式?

但是,我不想停止,如果一個失敗。我想繼續,然後一起報告所有故障。

例子:

[TestMethod] 
public void Test() 
{ 
    foreach (item in list) 
    { 
     // if fail, continue on with the rest 
     Assert(if fail, add to output list); 
    } 

    output_failures_all_at_once; 
} 

回答

3

我會做這樣的事情:

// Assert that each item name is fewer than 8 characters. 
[TestMethod] 
public void Test() 
{ 
    List<string> failures = new List<string>(); 

    // However you get your list in the first place 
    List<Item> itemsToTest = GetItems(); 

    foreach (Item item in itemsToTest) 
    { 
     // if fail, continue on with the rest 
     if (item.Name.Length > 8) 
     { 
     failures.Add(item.Name); 
     } 
    } 

    foreach (string failure in failures) 
    { 
     Console.WriteLine(failure); 
    } 

    Assert.AreEqual(0, failures.Count); 
} 
+0

儘管如此,它並未斷言每個項目。你能解釋失敗的方法嗎? – Zach

+0

你說得對,它沒有聲明每個項目。 fail()方法是你正在測試的東西。我會重寫它以顯示更明確的示例。 –

0

您可以嘗試湯姆的建議,而不是

foreach (string failure in failures) 
{ 
    Console.WriteLine(failure); 
} 

var errorMessage = failures.Aggregate((current, next) => current + ", " + next); 
Assert.AreEqual(0, failures.Count, errorMessage); 

順便提一下,失敗方法應該包含檢測項目中的失敗的邏輯。

+0

感謝您解釋失敗的方法。 – Zach