NUnit/xUnit 提供優雅的 `Assert.Throws
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
public static class ExceptionAssert
{
///
/// 執行動作並期望拋出任意異常
///
public static Exception Throws(Action action, string message = null)
{
try { action(); }
catch (Exception ex) { return ex; }
throw new AssertFailedException(message ?? "預期會拋出異常,但未拋出。");
}
///
/// 執行動作並期望拋出指定型別異常 (含繼承關係)
///
public static T Throws(Action action, string message = null) where T : Exception
{
try { action(); }
catch (Exception ex)
{
if (ex is T typed) return typed;
throw new AssertFailedException(
message ?? $"預期拋出 {typeof(T).Name},實際拋出 {ex.GetType().Name}。");
}
throw new AssertFailedException(
message ?? $"預期拋出 {typeof(T).Name},但未拋出異常。");
}
///
/// 執行異步動作並期望拋出指定異常
///
public static async Task ThrowsAsync(Func action, string message = null) where T : Exception
{
try { await action(); }
catch (Exception ex)
{
if (ex is T typed) return typed;
throw new AssertFailedException(
message ?? $"預期拋出 {typeof(T).Name},實際拋出 {ex.GetType().Name}。");
}
throw new AssertFailedException(
message ?? $"預期拋出 {typeof(T).Name},但未拋出異常。");
}
///
/// 驗證動作「不拋出」指定異常
///
public static void DoesNotThrow(Action action, string message = null) where T : Exception
{
try { action(); }
catch (T ex)
{
throw new AssertFailedException(
message ?? $"不預期拋出 {typeof(T).Name},但拋出了:{ex.Message}");
}
}
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void WriteToTextFile_OldStyle()
{
PDFUtility.WriteToTextFile("D:ACA.pdf", null);
// 問題:若前面程式碼也拋 ArgumentNullException 會誤判通過
}
[TestMethod]
public void WriteToTextFile_NewStyle()
{
// 精確指定「這個 Lambda」應拋出異常
var ex = ExceptionAssert.Throws(() =>
PDFUtility.WriteToTextFile("D:ACA.pdf", null),
"輸出檔案路徑不應為 null");
// 進一步驗證異常屬性
Assert.AreEqual("filePath", ex.ParamName);
Assert.IsTrue(ex.Message.Contains("ACA.pdf"));
}
[TestMethod]
public async Task AsyncMethod_ThrowsValidationException()
{
var ex = await ExceptionAssert.ThrowsAsync(() =>
service.ProcessOrderAsync(null));
Assert.AreEqual("OrderCannotBeNull", ex.ErrorCode);
}
[TestMethod]
public void ValidInput_DoesNotThrow()
{
ExceptionAssert.DoesNotThrow(() =>
validator.Validate(new ValidModel()));
}
public static T ThrowsWithMessage(Action action, string expectedMessage, StringComparison comparison = StringComparison.Ordinal)
where T : Exception
{
var ex = Throws(action);
if (!ex.Message.Contains(expectedMessage, comparison))
{
throw new AssertFailedException(
$"異常訊息不符。預期包含:'{expectedMessage}',實際:'{ex.Message}'");
}
return ex;
}
// 使用
var ex = ExceptionAssert.ThrowsWithMessage(
() => validator.Validate(null), "不得為空");
[TestClass]
public abstract class TestBase
{
protected static ExceptionAssert Ex => new ExceptionAssert(); // 或直接靜態呼叫
}
using static MyTestHelpers.ExceptionAssert;
[TestMethod]
public void Test()
{
Throws(() => DoSomething(null));
}
安裝 `FluentAssertions` NuGet 套件,獲得更豐富的斷言語法:
// 需安裝 FluentAssertions
action.Should().Throw()
.WithMessage("*不得為空*")
.And.ParamName.Should().Be("filePath");
// Action 代表「無參數、無回傳」的程式碼區塊
Action action = () => PDFUtility.WriteToTextFile("D:ACA.pdf", null);
// 執行時機完全由 Throws 方法控制
try
{
action(); // 這裡才真正執行
}
catch (Exception ex) { ... }
這叫 延遲執行,讓測試框架能精確控制「何時執行、如何捕獲異常」。
MSTest 透過擲回 `AssertFailedException` 判定測試失敗,區別於一般例外。這是 MSTest 內部機制,自訂斷言必須拋出此型別。
自行實作 `ExceptionAssert.Throws` 僅需 30 行程式碼,即可賦予 MSTest 接近 NUnit/xUnit 的異常斷言能力:精確範圍、型別安全、異常物件回傳、支援非同步。搭配 `DoesNotThrow`、`ThrowsWithMessage` 形成完整異常驗證工具箱。長期專案強烈建議引入 FluentAssertions 獲得業界標準的流暢斷言體驗。