【问题标题】:Unit test not reaching a piece of code单元测试没有达到一段代码
【发布时间】:2010-08-30 19:45:53
【问题描述】:

我是单元测试的新手。我想做如下事情:

[Test]
[ExpectedException(ExceptionType = typeof(Exception))]
public void TestDeleteCategoryAssociatedToTest()
{
    Category category = CategoryHelper.Create("category", Project1);
    User user;
    Test test1 = IssueHelper.Create(Project1, "summary1", "description1", user);
    test1.Category = category;
    category.Delete(user);          
    Assert.IsNotNull(Category.Load(category.ID));
    Assert.IsNotNull(Test.Load(test1.ID).Category);
}

我的目的是通过执行Assert.IsNotNull()... 来测试该类别是否未被删除,但由于它引发了异常,因此它没有到达那段代码。知道如何改进上述测试吗?

实际上,在我的 API 中,如果类别与测试相关联,我会抛出异常... 我的 sn-p 是:

 IList<Test> tests= Test.LoadForCategory(this);
 if (tests.Count > 0)
 {
     throw new Exception("Category '" + this.Name + "' could not be deleted because it has items assigned to it.");
 }
 else
 {
     base.Delete();
     foreach (Test test in tests)
     {
         test.Category = null;
     }
 }

【问题讨论】:

  • 您是否要删除该类别?我无法理解您的代码流程。 category.Delete(user) 做什么?这就是问题所在吗?
  • 我认为他正在尝试检查,删除异常没有被不必要地抛出

标签: c# unit-testing


【解决方案1】:

每次测试只测试一项功能。 IOW 编写单独的成功和失败测试。

【讨论】:

    【解决方案2】:

    你可以这样做:

    [Test]
    public void TestDeleteCategoryAssociatedToTest()
    {
        // Arrange
        Category category = CategoryHelper.Create("category", Project1);
        User user;
        Test test1 = IssueHelper.Create(Project1, "summary1", "description1", user);
        test1.Category = category;
    
        try
        {
            // Act
            category.Delete(user);
    
            // Assert       
            Assert.Fail("The Delete method did not throw an exception.");
        }
        catch
        {
            Assert.IsNotNull(Category.Load(category.ID));
            Assert.IsNotNull(Test.Load(test1.ID).Category);
        }
    }
    

    Assert.Fail() 告诉,如果没有抛出异常,单元测试将失败。 如果出现异常,您可以进行其他检查,如上所示。

    【讨论】:

      猜你喜欢
      • 2019-11-03
      • 1970-01-01
      • 2014-09-08
      • 1970-01-01
      • 2010-11-19
      • 1970-01-01
      • 2010-12-03
      • 2012-03-26
      • 2014-03-25
      相关资源
      最近更新 更多