如何配置FluentAssertions检测未对比属性并抛出异常?
解决方案:使用FluentAssertions检测对象多余属性(含嵌套结构)
FluentAssertions内置了严格等价性检查的配置,能够直接满足你「源对象存在目标对象没有的属性时抛出异常」的需求,无需手动实现深层属性遍历。
核心配置:启用Strict模式
通过.Strict()选项可以强制要求两个对象的属性完全匹配(包括嵌套对象),当源对象存在目标对象未定义的属性时,测试会直接失败并抛出异常。
修正后的测试代码
将你的测试用例修改为以下形式:
public class CompareClassTest { public class ClassA { public int Property1 { get; set; } public string Property2 { get; set; } } public class ClassB { public int Property1 { get; set; } public string Property2 { get; set; } public bool Property3 { get; set; } } [Test] public void TestEquivalence() { var objA = new ClassB { Property1 = 1, Property2 = "Test", Property3 = true }; var objB = new ClassA { Property1 = 1, Property2 = "Test" }; objA.Should().BeEquivalentTo(objB, options => options .Strict() // 开启严格模式,检查属性完全匹配 .IncludingAllDeclaredProperties() // 包含所有声明的属性 .IncludingNestedObjects()); // 遍历嵌套对象结构 } }
运行该测试会直接失败,提示Property3是源对象中多余的属性。
为什么之前的配置无效?
ThrowingOnMissingMembers():该选项的作用是当目标对象缺少源对象需要检查的属性时抛出异常,与你的需求逻辑相反(你需要检测的是源对象有目标对象没有的属性)。- 单纯的
IncludingAllDeclaredProperties():未开启严格模式时,FluentAssertions只会验证目标对象存在的属性,自动忽略源对象的多余属性。
验证嵌套对象场景
如果你的对象包含多层嵌套结构,Strict模式同样能检测到嵌套对象中的多余属性:
public class NestedClassA { public int NestedProp1 { get; set; } } public class NestedClassB { public int NestedProp1 { get; set; } public string NestedProp2 { get; set; } } public class ParentClassA { public NestedClassA Nested { get; set; } } public class ParentClassB { public NestedClassB Nested { get; set; } } [Test] public void TestNestedEquivalence() { var parentB = new ParentClassB { Nested = new NestedClassB { NestedProp1 = 2, NestedProp2 = "Extra" } }; var parentA = new ParentClassA { Nested = new NestedClassA { NestedProp1 = 2 } }; parentB.Should().BeEquivalentTo(parentA, options => options .Strict() .IncludingAllDeclaredProperties() .IncludingNestedObjects()); }
该测试会失败,明确指出嵌套对象中的NestedProp2是多余属性。
自定义精细控制
如果需要忽略特定的多余属性,可以结合Excluding方法:
objA.Should().BeEquivalentTo(objB, options => options .Strict() .Excluding(x => x.Property3) // 忽略指定的多余属性 .IncludingAllDeclaredProperties() .IncludingNestedObjects());
内容的提问来源于stack exchange,提问作者rklec
相关产品推荐
相关产品推荐

