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

如何在C#中使用Fluent Assertions收集断言失败且不捕获异常?

使用Fluent Assertions收集断言失败的无异常捕获方案

你可以利用Fluent Assertions原生的断言作用域能力,无需通过捕获异常来收集失败信息。核心是借助AssertionScope的Discard()方法,直接提取验证失败的消息,同时避免抛出异常。

单字段验证的改写实现

private static void AssertValue(object? actual, object? expected, string fieldName, IDictionary<string, string> assertionFailures)
{
    using var scope = new AssertionScope(fieldName);
    actual.Should().BeEquivalentTo(expected);
    
    // 提取所有失败消息,终止作用域且不抛出异常
    var failures = scope.Discard();
    if (failures.Any())
    {
        assertionFailures.Add(fieldName, string.Join(Environment.NewLine, failures));
    }
}

关键说明

  • Discard()方法会结束当前断言作用域,返回所有已收集的失败信息,同时不会触发异常抛出,完美替代原有的try-catch逻辑。
  • 若断言通过,failures为空集合,不会向结果字典中添加条目。
  • 用string.Join合并多条失败消息,和原代码中捕获异常时的e.Message输出格式保持一致。

批量字段验证的优化实现

如果需要验证多个字段,还可以在一个全局断言作用域中完成所有验证,一次性提取所有失败:

private static void AssertAllValues(IDictionary<string, (object? Actual, object? Expected)> fields, IDictionary<string, string> assertionFailures)
{
    using var scope = new AssertionScope();
    foreach (var (fieldName, pair) in fields)
    {
        pair.Actual.Should().BeEquivalentTo(pair.Expected, because: $"字段 {fieldName} 不匹配");
    }
    
    var failures = scope.Discard();
    foreach (var failure in failures)
    {
        assertionFailures.Add(ExtractFieldName(failure), failure);
    }
}

// 辅助方法:从失败消息中提取字段名(根据实际断言消息格式调整)
private static string ExtractFieldName(string failureMessage)
{
    var index = failureMessage.IndexOf("字段 ", StringComparison.Ordinal);
    if (index >= 0)
    {
        var endIndex = failureMessage.IndexOf(" 不匹配", StringComparison.Ordinal);
        if (endIndex > index)
        {
            return failureMessage.Substring(index + 2, endIndex - index - 2);
        }
    }
    return "未知字段";
}

这种方式能更高效地批量收集所有断言失败,彻底避免异常捕获带来的性能开销。

内容的提问来源于stack exchange,提问作者Patrik Mihalčin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 18:15:51