You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Fluent Assertions中使用非硬编码异常类型的Should().Throw()?

解决Fluent Assertions参数化异常类型的问题

Fluent Assertions提供了非泛型的Throw(Type)重载,刚好能满足你参数化异常类型的需求。直接把存储异常类型的Type变量传入该方法即可,后续的断言逻辑(比如.Where())和泛型版本用法完全一致。

示例代码:

// 定义参数化的异常类型变量
Type expectedExceptionType = typeof(MyException);

Action act = () => sut.MyMethod();
act.Should().Throw(expectedExceptionType).Where(myPredicate);

如果需要严格匹配异常类型(不匹配子类),可以用ThrowExactly(expectedExceptionType);如果允许匹配自身或子类,就用上面的Throw方法,按需选择即可。

内容的提问来源于stack exchange,提问作者g.pickardou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 03:51:57