如何使用FluentAssertions检查嵌套属性的类型是否相同?
使用FluentAssertions验证嵌套属性的类型一致性
你希望用FluentAssertions检查两个实例的嵌套属性类型是否一致,具体场景如下:
类定义
class Item { public int? Value { get; set; } public Exception? Exception { get; set; } }
测试代码
[Fact] public void Test() { var expected = new[] { new Item { Value = 1 }, new Item { Exception = new TimeoutException() }, }; var actual= new[] { new Item { Value = 1 }, new Item { Exception = new TimeoutException() }, }; actual.Should().BeEquivalentTo(expected); }
由于两个TimeoutException实例不同,测试失败。你不需要检查实例是否相等,只需验证它们的类型是否相同,询问如何实现。
你自己已实现预期行为,但觉得不够优雅:
actual.Should().BeEquivalentTo(expected, options => options .Using<Item>(context => { if (context.Expectation.Exception is { Exception: { } a } && context.Subject.Exception is { Exception: { } b }) { a.Should().BeOfType(b.GetType()); } }) .WhenTypeIs<Item>());
更优雅的实现方式
可以直接针对Exception类型单独配置比较规则,无需在Item层面嵌套判断,逻辑更清晰简洁:
actual.Should().BeEquivalentTo(expected, options => options .Using<Exception>(ctx => ctx.Subject.Should().BeOfType(ctx.Expectation.GetType())) .WhenTypeIs<Exception>());
说明
- 该配置会让FluentAssertions在比较
Exception类型的属性时,仅校验两者的类型是否一致,跳过实例相等性检查。 - 相比你之前的写法,直接聚焦目标类型
Exception设置规则,避免了冗余的嵌套判断,代码更简洁易维护。
内容的提问来源于stack exchange,提问作者SuperJMN
相关产品推荐
相关产品推荐

