อีกทางเลือกหนึ่งในการใช้ExpectedException
แอตทริบิวต์บางครั้งฉันกำหนดวิธีการที่เป็นประโยชน์สองวิธีสำหรับชั้นเรียนทดสอบของฉัน
AssertThrowsException()
รับผู้รับมอบสิทธิ์และยืนยันว่าจะส่งข้อยกเว้นที่คาดไว้พร้อมกับข้อความที่คาดไว้
AssertDoesNotThrowException()
ใช้ผู้รับมอบสิทธิ์คนเดียวกันและยืนยันว่าไม่มีข้อยกเว้น
การจับคู่นี้มีประโยชน์มากเมื่อคุณต้องการทดสอบว่ามีข้อยกเว้นเกิดขึ้นในกรณีหนึ่ง แต่ไม่ใช่อีกกรณีหนึ่ง
การใช้รหัสทดสอบหน่วยของฉันอาจมีลักษณะดังนี้:
ExceptionThrower callStartOp = delegate(){ testObj.StartOperation(); };
AssertThrowsException(callStartOp, typeof(InvalidOperationException), "StartOperation() called when not ready.");
testObj.Ready = true;
AssertDoesNotThrowException(callStartOp);
สวยและเรียบร้อยเหรอ?
My AssertThrowsException()
และAssertDoesNotThrowException()
method ถูกกำหนดบนคลาสพื้นฐานทั่วไปดังนี้:
protected delegate void ExceptionThrower();
protected void AssertThrowsException(ExceptionThrower exceptionThrowingFunc, Type expectedExceptionType, string expectedExceptionMessage)
{
try
{
exceptionThrowingFunc();
Assert.Fail("Call did not raise any exception, but one was expected.");
}
catch (NUnit.Framework.AssertionException)
{
throw;
}
catch (Exception ex)
{
Assert.IsInstanceOfType(expectedExceptionType, ex, "Exception raised was not the expected type.");
Assert.IsTrue(ex.Message.Contains(expectedExceptionMessage), "Exception raised did not contain expected message. Expected=\"" + expectedExceptionMessage + "\", got \"" + ex.Message + "\"");
}
}
protected void AssertDoesNotThrowException(ExceptionThrower exceptionThrowingFunc)
{
try
{
exceptionThrowingFunc();
}
catch (NUnit.Framework.AssertionException)
{
throw;
}
catch (Exception ex)
{
Assert.Fail("Call raised an unexpected exception: " + ex.Message);
}
}