使用FluentAssertions的AssertionScopes收集所有失败?
解读
国内单元测试面试常把“能否一次性收集所有断言失败”作为区分“只会写Assert.AreEqual”与“真正写过可维护测试”的关键题。
FluentAssertions的AssertionScope正是为此而生:它把其后所有断言的异常先缓存,直到作用域结束才一次性抛出AggregateException。
面试官通常想确认三点:
- 知道用using var scope = new AssertionScope();
- 知道失败不会立即中断,而是累积;
- 知道如何读取scope内的所有失败信息,或自定义报告格式。
知识点
- AssertionScope 类位于 FluentAssertions.Execution 命名空间
- 构造函数支持自定义失败策略(如ContinueOnFailure)
- Dispose() 时触发断言汇总,默认抛出MultiAssertionException(继承AggregateException)
- 可配合AssertionScope.Current.FailWith手动添加失败
- 与xUnit/NUnit/MSTest均无冲突,但需保证测试运行器能捕获AggregateException
- 线程安全:同一异步上下文共享一个Scope,异步测试需小心ConfigureAwait(false)带来的上下文切换
答案
using FluentAssertions;
using FluentAssertions.Execution;
using Xunit;
public class OrderDto
{
public int Id { get; set; }
public string Customer { get; set; }
public decimal Amount { get; set; }
}
public class AssertionScopeDemo
{
[Fact]
public void ValidateOrder_ShouldCollectAllFailures()
{
var order = new OrderDto { Id = 0, Customer = null, Amount = -10 };
// 关键:using var scope
using var scope = new AssertionScope();
order.Id.Should().BePositive("订单号必须为正");
order.Customer.Should().NotBeNullOrWhiteSpace("客户名称不能为空");
order.Amount.Should().BePositive("金额必须大于0");
// 当离开using块时,所有失败会被一次性抛出:
// MultiAssertionException:
// Expected order.Id to be positive, but found 0.
// Expected order.Customer not to be <null> or whitespace, but found <null>.
// Expected order.Amount to be positive, but found -10.
}
}
若需自定义报告,可继承AssertionStrategy或在CI中捕获MultiAssertionException并序列化其Messages。
拓展思考
- 与Record.Exception模式对比:Record.Exception只能抓第一个异常,AssertionScope可抓全部,且语法更贴近自然语言。
- 在SpecFlow/BDD场景下,可把AssertionScope封装进StepBase,实现“一个Scenario只报一次汇总错误”,减少流水线日志刷屏。
- 性能注意:Scope内失败越多,字符串拼接开销越大;对千级断言的基准测试,建议分片或并行执行后再合并报告。
- 异步流测试:在await前后若出现上下文切换,需保证Scope在同一ExecutionContext内,可改用AsyncLocal<AssertionScope>做传递,或直接把Scope放在异步方法最外层。