FluentAssertions如何校验集合包含指定列表的等价元素子集
问题描述
现有如下匿名类型集合:
new[] { new { A = 5, PropIDontCareAbout = "XXX" }, new { A = 7, PropIDontCareAbout = "XXX" }, new { A = 9, PropIDontCareAbout = "XXX" } }
校验要求如下:
- 不限制集合内元素的排列顺序
- 实际集合至少包含
new { A = 5 }、new { A = 9 }两个等价元素 - 校验过程自动忽略
PropIDontCareAbout这类无需关注的多余属性 - 无法使用
Contains方法:该方法要求实际集合与预期集合的元素类型完全一致,无法适配不同匿名类型的等价匹配场景
当前通过循环逐个调用ContainEquivalentOf的实现代码:
var actual = new[] { new { A = 5, PropIDontCareAbout = "XXX" }, new { A = 7, PropIDontCareAbout = "XXX" }, new { A = 9, PropIDontCareAbout = "XXX" } }; var expected = new [] { new { A = 5 }, new { A = 9 } }; foreach (var expectedItem in expected) { actual.Should().ContainEquivalentOf(expectedItem); }
需要找到更简便的批量校验写法,替代手动循环逻辑。
最简实现
直接使用FluentAssertions的等价校验配置即可,无需手动循环:
var actual = new[] { new { A = 5, PropIDontCareAbout = "XXX" }, new { A = 7, PropIDontCareAbout = "XXX" }, new { A = 9, PropIDontCareAbout = "XXX" } }; var expected = new [] { new { A = 5 }, new { A = 9 } }; actual.Should().BeEquivalentTo(expected, opt => opt.ExcludingMissingMembers());
配置说明
BeEquivalentTo默认不校验元素顺序,符合顺序无关的要求ExcludingMissingMembers()配置会自动跳过预期对象不存在、实际对象存在的属性匹配,正好过滤掉PropIDontCareAbout这类不需要校验的多余属性- 该写法天然支持不同类型的对象等价比较,不需要实际集合和预期集合的元素类型完全一致
- 校验逻辑会自动遍历所有预期元素,确认每个元素都在实际集合中存在等价项,和手动循环调用
ContainEquivalentOf的效果完全一致,代码更简洁。
如果需要自定义更多匹配规则,比如指定忽略特定名称的属性、调整数值匹配精度等,可以直接在opt配置委托中追加对应规则即可。
内容的提问来源于stack exchange,提问作者THX-1138
相关产品推荐
相关产品推荐

