与IndexOutOfRangeException相关的问题

时间:2011-07-10 17:08:56

标签: c#

我在c#代码中遇到IndexOutOfRangeException的连续错误。代码段如下:

public void GetAccountSalesDataTestWithAccountsIncluded()
{
    AccountSalesDataRepository target = new AccountSalesDataRepository();
    AccountSalesDataSearchCriteria[] searchCriteria = new AccountSalesDataSearchCriteria[2]
     {   
        new AccountSalesDataSearchCriteria
        {
             ProgramAccountId = new AccountSalesDataSearchCriteria.SearchCriteria<int>[1] { new AccountSalesDataSearchCriteria.SearchCriteria<int>(98, true) }
        },
        new AccountSalesDataSearchCriteria()
     };

    AccountSalesDataSummary[] results;
    results = target.GetAggregateAccountSalesData(searchCriteria, true);
    try
    {
        Assert.IsNotNull(results, "The result set should not be null with the given account");
        Assert.IsTrue(results.Length > 0, "The result set should not be empty with given account");
    }
    catch (AssertFailedException /*ex*/)
    {
    }
    this.AccountSalesDataSummaryBasicTest(results, true);
    try
    {
        Assert.AreEqual(results[0].AccountId, 2);
        Assert.AreEqual(results[0].TotalPurchaseAmount, decimal.Parse("200"), "The total purchase amount is incorrect");
        Assert.AreEqual(results[0].TotalPurchaseQuantity, 2000, "The total purchase quantity is incorrect");
        Assert.AreEqual(results[0].TotalSaleQuantity, double.Parse("200"), "The total sales quantity is incorrect");
        Assert.AreEqual(results[0].TotalSalesAmount, decimal.Parse("20"), "The total sales amount is incorrect");
    }
    catch (AssertFailedException /*ex*/)
    {
    }
}

这可能是什么原因?

请原谅我,如果我可能认为我与我的概念不一致,因为我对这一切都很陌生。

1 个答案:

答案 0 :(得分:4)

你显然正在编写单元测试。 AssertFailedException表示你的一个断言失败了,它应该 not 被捕获,因为整个点是如果断言失败,你的整个测试应该失败(有没有必要继续测试,因为你已经知道出了什么问题)。此外,当您捕获异常并且在catch块中没有执行任何操作时,您实际上是在说“如果抛出异常,则忽略它并继续”。因此,应该检查数组实际包含某些内容的断言是否可以完成其工作,但是您将其静音并使测试继续进行,即使数组为空 - 因此下一个IndexOutOfRangeException中的try块。

删除try / catch块(保留try块的内容),您将看到测试失败并告诉您确切的错误:数组为空。它是空的原因是要么GetAggregateAccountSalesData()中存在错误(优秀,测试帮助您找到错误),或者您调用错误,或者测试数据丢失(是否存在帐户销售)可以聚合的数据?),或某些东西在某种程度上没有正确设置(你需要调用一些其他方法才能使GetAggregateAccountSalesData()工作吗?)尝试调试测试,看看该方法内部发生了什么。

相关问题