views:

76

answers:

2

I am new to unit testing. I want to do something as follows:

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

My aim here is to test that the category wasn't deleted by doing the Assert.IsNotNull()... but since it's throwing the exception, it's not reaching that piece of code. Any idea how I can improve on the above test?

Actually in my API I throw an exception in case the category is associated to a Test... My snippet is:

 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;
     }
 }
+9  A: 

Try and test only one functionality per test. IOW write separate success and failure tests.

leppie
+1  A: 

You could do something like:

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

The Assert.Fail() tells, that the Unit Test shall fail, if no exception has been thrown. In case of an exception you can do other checks, like shown above.

BitKFu