2011-08-18 88 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