ThrowingException 导致单元测试中断?

ThrowingException Causing UnitTest Break?

我遇到这样一种情况,在某些情况下实际函数抛出异常,我为它编写了单元测试,但不幸的是单元测试失败了。

示例代码:

// 'CheckNumber()' function is Present in 'Number' class.

public int CheckNumber(int Number)
{
    if (Number < 0 || Number > MaxNumber) // MaxNumber = 300
       throw new ArgumentOutOfRangeException();

    //..     
}     

单元测试:

我正在使用 NUnit 框架

// When The Number is Less than Zero Or Greater than Maximun Number

[Test]
public void CheckNumberTest()
{
   Number number = new Number();
   int returnedValue = number.CheckNumber(-1);

   // Assertion.
   Assert.That(returnedValue , Throws.ArgumentOutOfRangeException);
}

当我 运行 测试时,此测试失败。这个测试实际上是在抛出异常并且 TestMethod 要中断?那么如何解决呢?

请检查文档 here

您当然需要了解同一 link 中异常之间的差异 这应该可以帮助您彻底

// Require an ApplicationException - derived types fail!
Assert.Throws( typeof(ApplicationException), code );
Assert.Throws<ApplicationException>()( code );

// Allow both ApplicationException and any derived type
Assert.Throws( Is.InstanceOf( typeof(ApplicationException), code );
Assert.Throws( Is.InstanceOf<ApplicationException>(), code );

// Allow both ApplicationException and any derived type
Assert.Catch<ApplicationException>( code );

// Allow any kind of exception
Assert.Catch( code )

这里的问题是您的方法没有 return 任何值,而是抛出异常。

int returnedValue = number.CheckNumber(-1); //throws ArgumentOutOfRangeException

测试代码像其他所有代码一样执行,它会在有人捕获之前冒出异常。在您的情况下,它被测试执行程序捕获,因为您在这里没有任何 try/catch 块。

编写测试的正确方法是使用 Assert.Throws<TException>.

[Test]
public void CheckNumberTest()
{
    //Arrange
   Number number = new Number();

   //Act
   var throws = new TestDelegate(() => number.CheckNumber(-1));

   //Assert.
   Assert.Throws<ArgumentOutOfRangeException>(throws);
}