1

我有一个简单的测试方法

public double Divide(double numerator, double denominator)       
{
    if (denominator == 0)
    {
        throw new NullReferenceException("Cannot divide by zero.");
    }
    return numerator / denominator;
}

现在我的测试用例数据文件看起来像这样

<TestCase>
    <Numerator>-2.5</Numerator>
    <Denominator>1</Denominator>
    <ExpectedResult>-2.5</ExpectedResult>
</TestCase>
<TestCase>
    <Numerator>55</Numerator>
    <Denominator>5</Denominator>
    <ExpectedResult>11</ExpectedResult>
</TestCase>
<TestCase>
    <Numerator>5</Numerator>
    <Denominator>0</Denominator>
    <ExpectedResult>DivideByZeroException</ExpectedResult>
</TestCase>

将所有这些测试用例包含在单个测试方法中的方法应该是什么。我的基本问题是处理异常测试方法。我知道我可以在测试方法中使用 [ExpectedException(typeof(DivideByZeroException)] 属性,但在这种情况下,此方法不适合其他 2 个测试 csaes。

有人可以帮助我如何将所有这些测试用例容纳到一个方法中。

4

2 回答 2

0

您可以捕获DivideByZeroException内部测试方法,然后Assert.Sucess();(在 catch 块内)

于 2009-12-18T13:20:07.417 回答
0

像这样的东西:

public void TestQuotients() {
    try {
      // do the test which causes divide by 0
      int x = 0;
      int y = 10 / x;

      Assert.Fail("should have gotten exception");
    }
    catch (DivideByZeroException e) {
      // expected behavior
    }

    try {
      // do the next test which causes divide by 0
      int k = 0;
      int t = 100 / k;
      Assert.Fail("should have gotten exception");
    }
    catch (DivideByZeroException e) {
      // expected behavior
    }

    // this test doesn't cause exception
    double x = 100;
    double y = 10;
    Assert.AreEqual(10,x/y,"The quotient is wrong.");
}
于 2009-12-18T13:21:07.457 回答