Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 单元测试未达到一段代码_C#_Unit Testing - Fatal编程技术网

C# 单元测试未达到一段代码

C# 单元测试未达到一段代码,c#,unit-testing,C#,Unit Testing,我不熟悉单元测试。我想做以下几件事: [Test] [ExpectedException(ExceptionType = typeof(Exception))] public void TestDeleteCategoryAssociatedToTest() { Category category = CategoryHelper.Create("category", Project1); User user; Test test1 = IssueHelper.Creat

我不熟悉单元测试。我想做以下几件事:

[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;
     }
 }
IList tests=Test.LoadForCategory(此);
如果(tests.Count>0)
{
抛出新异常(“Category'+this.Name+”,无法删除,因为它有分配给它的项。”);
}
其他的
{
base.Delete();
foreach(测试中的测试)
{
test.Category=null;
}
}

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

您可以执行以下操作:

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

是否尝试删除该类别?我无法理解您的代码流程。category.Delete(用户)做什么?这就是问题所在吗?我想他是在检查,删除异常没有被不必要地抛出