C# 导致单元测试中断的异常?
我有一种情况,在某些情况下,实际函数抛出异常,我为此编写了单元测试,但不幸的是,单元测试失败了 示例代码:C# 导致单元测试中断的异常?,c#,unit-testing,nunit,C#,Unit Testing,Nunit,我有一种情况,在某些情况下,实际函数抛出异常,我为此编写了单元测试,但不幸的是,单元测试失败了 示例代码: // 'CheckNumber()' function is Present in 'Number' class. public int CheckNumber(int Number) { if (Number < 0 || Number > MaxNumber) // MaxNumber = 300 throw new ArgumentOutOfRan
// 'CheckNumber()' function is Present in 'Number' class.
public int CheckNumber(int Number)
{
if (Number < 0 || Number > MaxNumber) // MaxNumber = 300
throw new ArgumentOutOfRangeException();
//..
}
当我运行测试时,此测试失败。这个测试实际上是在抛出异常,TestMethod是否会中断?那么如何修复它呢?请查看文档 当然,您需要了解同一链接中异常之间的差异 这应该有助于你彻底了解
// 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 )
//需要ApplicationException-派生类型失败!
抛出(typeof(ApplicationException),代码);
Assert.Throws()(代码);
//允许ApplicationException和任何派生类型
Assert.Throws(Is.InstanceOf(typeof(ApplicationException))代码);
Assert.Throws(Is.InstanceOf(),代码);
//允许ApplicationException和任何派生类型
Assert.Catch(代码);
//允许任何类型的例外
Assert.Catch(代码)
这里的问题是,您的方法不返回任何值,而是抛出异常
int returnedValue = number.CheckNumber(-1); //throws ArgumentOutOfRangeException
测试代码会像其他代码一样执行,在有人捕获它之前,它会冒泡异常。在您的情况下,它被测试执行器捕获,因为您没有任何try/catch块
编写测试的正确方法是使用Assert.Throws
[测试]
public void CheckNumberTest()
{
//安排
编号=新编号();
//表演
var throws=newtestdelegate(()=>number.CheckNumber(-1));
//断言。
Assert.Throws(抛出);
}
尝试使用Assert.Throws(()=>您的函数)
我尝试了这个:但测试仍然失败!Assert.Throws(()=>CheckNumberTest)
@johnny
int returnedValue = number.CheckNumber(-1); //throws ArgumentOutOfRangeException
[Test]
public void CheckNumberTest()
{
//Arrange
Number number = new Number();
//Act
var throws = new TestDelegate(() => number.CheckNumber(-1));
//Assert.
Assert.Throws<ArgumentOutOfRangeException>(throws);
}