2010-08-30 32 views
2

我是单元测试新手。我想要做的事如下:单元测试没有达到一段代码

[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我扔在案件类别关联到一个测试异常... 我的片段是:

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

你试图删除类别?我无法理解你的代码流。 category.Delete(用户)做了什么?这是问题所在吗? – Rahul 2010-08-30 11:13:21

+0

我认为他试图检查,删除异常没有被非正式抛出 – BitKFu 2010-08-30 11:19:59

回答

9

尝试和测试每个测试只有一个功能。 IOW编写单独的成功和失败测试。

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