มี 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
}
ความแตกต่าง
| Feature | Assert.ThrowsException | ExpectedException |
|---|---|---|
| ตรวจสอบ Exception Message | ได้ (Explicit) | ได้ (ใน Attribute) |
| เข้าถึง Exception Object | ได้ (Return Exception) | ไม่ได้ |
| หลาย Assert ใน Test เดียว | ได้ | ไม่ได้ (Fail ทันที) |
| Readability | ชัดเจนกว่า | สั้นกว่า |
แนะนำ: ใช้ Assert.ThrowsException เพื่อความยืดหยุ่นและอ่านง่าย