如何使用FluentAssertions捕获调用抛出的异常并断言自定义异常枚举值
在FluentAssertions中捕获并断言自定义异常的枚举值
基础异常捕获方式
FluentAssertions通过Should().Throw<T>()方法捕获代码执行过程中抛出的指定类型异常,这是官方文档基础示例的核心逻辑。
针对CustomException的枚举值断言
对于你定义的包含MyEnum属性的自定义异常,可在捕获异常后,通过链式调用Which访问异常实例,进而断言枚举值是否符合预期。
完整代码示例
假设有一个会抛出CustomException的业务方法:
public void TriggerException(MyEnum inputEnum) { throw new CustomException(inputEnum); }
对应的测试代码如下:
// 准备预期的枚举值 var targetEnum = MyEnum.TargetValue; // 将待测试代码包装为Action委托 Action testAction = () => TriggerException(targetEnum); // 执行断言:捕获异常并验证枚举值 testAction.Should().Throw<CustomException>() .Which.MyEnum.Should().Be(targetEnum);
关键细节说明
Action testAction = () => TriggerException(targetEnum):把要测试的代码包装成Action,让FluentAssertions能捕获执行过程中的异常。testAction.Should().Throw<CustomException>():断言执行该委托时会抛出CustomException类型的异常。.Which.MyEnum.Should().Be(targetEnum):通过Which拿到捕获到的异常实例,直接对其MyEnum属性做值断言。
如果需要同时验证异常的其他属性(比如异常消息),可以继续追加链式断言:
testAction.Should().Throw<CustomException>() .WithMessage("自定义异常提示文本") // 可选:验证异常消息 .Which.MyEnum.Should().Be(targetEnum);
内容的提问来源于stack exchange,提问作者user246392
相关产品推荐
相关产品推荐

