简体   繁体   English

单元测试未达到一段代码

[英]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(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. 我的目标是通过执行Assert.IsNotNull()来测试类别没有被删除...但是因为它抛出了异常,所以它没有达到那段代码。 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: 实际上在我的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;
     }
 }

Try and test only one functionality per test. 每次测试只尝试并测试一种功能。 IOW write separate success and failure tests. IOW分别编写成功和失败测试。

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. Assert.Fail()告诉我,如果没有抛出异常,单元测试将失败。 In case of an exception you can do other checks, like shown above. 如果发生异常,您可以进行其他检查,如上所示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM