Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Verify Exception ใน Unit Testing C#

มี 2 วิธีหลักใน MSTest:

1. Assert.ThrowsException (แนะนำ)

จับ Exception ได้ ตรวจสอบ Message/Type แบบ Explicit

[TestMethod]
public void Test_StringAppend_ThrowsException()
{
    var program = new Program();
    var ex = Assert.ThrowsException(() => program.StringAppend("Michael", "Jackson"));
    Assert.AreEqual("Test Exception", ex.Message);
}

2. ExpectedException Attribute

ประกาศบน Method คาดหวัง Exception Type และ Message

[TestMethod]
[ExpectedException(typeof(Exception), "Test Exception")]
public void Test_StringAppend_ThrowsException()
{
    var program = new Program();
    program.StringAppend("Michael", "Jackson"); // ถ้าไม่ Throw หรือ Message ผิด → Fail
}

ความแตกต่าง

FeatureAssert.ThrowsExceptionExpectedException
ตรวจสอบ Exception Messageได้ (Explicit)ได้ (ใน Attribute)
เข้าถึง Exception Objectได้ (Return Exception)ไม่ได้
หลาย Assert ใน Test เดียวได้ไม่ได้ (Fail ทันที)
Readabilityชัดเจนกว่าสั้นกว่า

แนะนำ: ใช้ Assert.ThrowsException เพื่อความยืดหยุ่นและอ่านง่าย