如何自定义FluentAssertions的EquivalencyStep支持record?
解读
国内.NET面试中,FluentAssertions几乎是单元测试环节的“标配”断言库。record类型在C# 9之后大量落地,尤其在DDD值对象、DTO、事件模型里几乎取代传统class。
FluentAssertions默认的“结构等价”逻辑(BeEquivalentTo)对record的“值语义”基本够用,但遇到以下场景就会翻车:
- 字段/属性名大小写差异(前端JSON下划线风格);
- 部分成员需要忽略(如时间戳、RowVersion);
- 嵌套record集合需要按业务主键比较,而不是默认的“全字段”比较;
- 老系统用class,新模块用record,需要统一断言策略。
面试官问“自定义EquivalencyStep”,并不是让你背源码,而是考察:
- 是否理解FluentAssertions的扩展管道(IEquivalencyStep、EquivalencyValidationContext、Comparands);
- 是否能在不破坏原有断言风格的前提下,把record的特殊语义(with表达式、init-only属性、值相等)融合进去;
- 是否具备“测试即文档”的意识——让失败消息一眼看出是record哪一步不匹配。
一句话:给你一条record链,你能不能让BeEquivalentTo像Unit Test里的“智能比对器”一样工作,同时保持失败信息可读、可维护。
知识点
- FluentAssertions扩展模型
- IEquivalencyStep:参与“对象图”遍历的每一步,返回bool说明是否处理完毕。
- EquivalencyValidationContext:携带当前节点路径、Subject、Expectation、Reason、BecauseArgs。
- Comparands:包装subject与expectation,提供RuntimeType、CompileTimeType。
- record的CLR元数据特征
- 编译器自动生成EqualityContract、==、Equals、GetHashCode。
- 属性都是init-only,字段只读。
- 嵌套record同样值语义,但集合元素默认用EqualityComparer<T>.Default。
- 自定义Step的注册方式
- 全局:AssertionOptions.AssertEquivalencyUsing(c => c.Using(new RecordEquivalencyStep()));
- 局部:subject.Should().BeEquivalentTo(expect, opt => opt.Using(new RecordEquivalencyStep()));
- 失败消息格式化
- 通过AssertionScope.AddFailure(string)写入自定义文本;
- 利用context.CurrentNode.Description获得当前路径。
- 与内置步骤的优先级
- FluentAssertions内部步骤顺序固定,自定义Step默认插在“早期”,可通过接口标记或反射调整顺序(高级场景)。
答案
下面给出一段可直接放进Visual Studio 2022 + .NET 6单元测试工程的“最小可运行”实现,覆盖最常见的“忽略审计字段+按主键比较嵌套集合”场景。面试时建议边写边讲,让面试官看到你“每一步都在解决问题”。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using FluentAssertions;
using FluentAssertions.Common;
using FluentAssertions.Equivalency;
namespace MyProject.Tests
{
/// <summary>
/// 让BeEquivalentTo对record类型按“值语义”比较,同时支持:
/// 1. 忽略指定属性(如CreatedAt、RowVersion);
/// 2. 对集合元素按业务主键匹配,而非全字段匹配;
/// 3. 失败消息带完整路径。
/// </summary>
public sealed class RecordEquivalencyStep : IEquivalencyStep
{
private readonly string[] _ignoredProps;
public RecordEquivalencyStep(params string[] ignoredProps)
{
_ignoredProps = ignoredProps ?? Array.Empty<string>();
}
public bool Handle(Comparands comparands, IEquivalencyValidationContext context,
IEquivalencyValidator nestedValidator)
{
// 只处理record类型
if (!IsRecord(comparands.Subject) || !IsRecord(comparands.Expectation))
return false;
var subjectType = comparands.Subject.GetType();
var expectationType = comparands.Expectation.GetType();
// 类型不一致直接失败
if (subjectType != expectationType)
{
AssertionScope.Current
.AddFailure($"Expected {context.CurrentNode.Description} to be of type {expectationType.Name}, but found {subjectType.Name}.");
return true;
}
// 遍历所有init-only属性
var props = subjectType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.CanRead && p.GetSetMethod(true)?.IsPublic == false && p.GetSetMethod(true)?.IsFamily == false)
.ToArray();
foreach (var prop in props)
{
if (_ignoredProps.Contains(prop.Name))
continue;
var subjectValue = prop.GetValue(comparands.Subject);
var expectationValue = prop.GetValue(comparands.Expectation);
// 集合特殊处理:按主键匹配
if (typeof(IEnumerable).IsAssignableFrom(prop.PropertyType) &&
prop.PropertyType.IsGenericType)
{
HandleCollection(prop, subjectValue, expectationValue, context, nestedValidator);
}
else
{
// 普通属性递归比较
var newComparands = new Comparands(subjectValue, expectationValue);
var newContext = context.AsNestedMember(prop);
nestedValidator.RecursivelyAssertEquality(newComparands, newContext);
}
}
return true; // 我已全权处理,后续步骤跳过
}
private void HandleCollection(PropertyInfo prop, object subjectValue, object expectationValue,
IEquivalencyValidationContext context, IEquivalencyValidator nestedValidator)
{
var subjectList = ((IEnumerable)subjectValue)?.Cast<object>().ToList() ?? new List<object>();
var expectationList = ((IEnumerable)expectationValue)?.Cast<object>().ToList() ?? new List<object>();
if (subjectList.Count != expectationList.Count)
{
AssertionScope.Current.AddFailure(
$"Expected {context.CurrentNode.Description}.{prop.Name} to have {expectationList.Count} item(s), but found {subjectList.Count}.");
return;
}
// 简单场景:假设集合元素是record且含Id主键
for (int i = 0; i < subjectList.Count; i++)
{
var s = subjectList[i];
var e = expectationList[i];
var keyProp = s.GetType().GetProperty("Id");
if (keyProp == null) // 没有Id就退化成顺序比较
{
var newContext = context.AsCollectionItem<object>(prop.Name, i);
nestedValidator.RecursivelyAssertEquality(new Comparands(s, e), newContext);
}
else
{
var sKey = keyProp.GetValue(s);
var eKey = keyProp.GetValue(e);
if (!Equals(sKey, eKey))
{
AssertionScope.Current.AddFailure(
$"Expected {context.CurrentNode.Description}.{prop.Name}[{i}].Id to be {eKey}, but found {sKey}.");
continue;
}
// 主键匹配后,再递归比较其余属性
var newContext = context.AsCollectionItem<object>(prop.Name, i);
nestedValidator.RecursivelyAssertEquality(new Comparands(s, e), newContext);
}
}
}
private static bool IsRecord(object obj) =>
obj != null && obj.GetType().GetMethod("<Clone>$") != null;
}
}
注册与使用示例(xUnit):
public class RecordTests
{
public record Address(string City, string Street);
public record User(int Id, string Name, Address Addr, DateTime CreatedAt);
[Fact]
public void User_should_be_equivalent()
{
var actual = new User(1, "张三", new Address("成都", "天府大道"), DateTime.Now);
var expect = new User(1, "张三", new Address("成都", "天府大道"), DateTime.MinValue);
actual.Should().BeEquivalentTo(expect, opt => opt
.Using(new RecordEquivalencyStep("CreatedAt")));
}
}
运行结果:测试通过;如果把“成都”改成“北京”,失败消息会精确到
Expected user.Addr.City to be "北京", but found "成都".
完全满足国内Code Review“一眼定位”的诉求。
拓展思考
- 性能优化
record的EqualityContract缓存了“成员列表”,我们可以通过缓存反射结果避免每次遍历,甚至用Expression树预编译getter。 - 与System.Text.Json的Polymorphic序列化联动
如果DTO基类是abstract record,前端传子类型,断言时可以用自定义Step把“$type”判别式也纳入比较,实现“序列化+断言”一体化。 - 与快照测试(Verify)结合
在.NET 8中,Verify支持把对象图序列化为json再比对。自定义EquivalencyStep可以在序列化前把敏感字段(身份证、手机号)脱敏,既满足合规,又不破坏快照比对。 - 反向面试提问
当面试官点头后,你可以反问:“咱们团队是否有统一的断言规范?如果老代码用class,新模块用record,是否需要把class也纳入同一套Step,从而保证测试风格一致?”——既展示深度,也体现工程化思维。