单元测试未达到一段代码

时间:2010-08-30 11:01:53

标签: c# unit-testing

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

[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中,如果类别与Test相关联,我会抛出异常... 我的片段是:

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

2 个答案:

答案 0 :(得分:9)

每次测试只尝试并测试一项功能。 IOW分别编写成功和失败测试。

答案 1 :(得分:1)

您可以执行以下操作:

[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()告诉我,如果没有抛出异常,单元测试将失败。 如果发生异常,您可以进行其他检查,如上所示。