【问题标题】:Visual Studio 2010 Unit Testing - Any way to continue a TestMethod after failed assertion?Visual Studio 2010 单元测试 - 断言失败后有什么方法可以继续测试方法?
【发布时间】:2011-08-18 16:02:56
【问题描述】:

我在 Visual Studio 2010 中有一个测试项目。我有一个 TestMethod。在这里面,我想遍历一个列表并测试每一个。所以,我有 1 个测试并且想要断言 N 次(列表中的每个项目一次)。

但是,如果失败,我不想停下来。我想继续,然后一起报告所有失败。

例子:

[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;
}

【问题讨论】:

    标签: c# visual-studio-2010 unit-testing


    【解决方案1】:

    我会这样做:

    // 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);
    }
    

    【讨论】:

    • 这并不针对每个项目进行断言。你能解释一下失败的方法吗?
    • 你是对的,它不会对每个项目都断言。 fail() 方法是你正在做的测试。我将重写它以显示一个更明确的示例。
    【解决方案2】:

    你可以试试汤姆的建议,而不是

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

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

    顺便说一句,fail 方法应该包含检测项目失败的逻辑

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-11
      • 2021-12-15
      • 2015-12-18
      • 1970-01-01
      • 1970-01-01
      • 2011-10-13
      • 2013-03-18
      相关资源
      最近更新 更多