Unit test not reaching a piece of code
I am new to unit testing. I want to do something as follows:
[Test]
[ExpectedException(ExceptionType = typeof(Excepti开发者_运维问答on))]
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;
}
}
Try and test only one functionality per test. IOW write separate success and failure tests.
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.
精彩评论