如何在FluentAssertions中使用Exclude作为集合中的属性?

我有两节课:

public class ClassA { public int? ID {get; set;} public IEnumerable Children {get; set;} } public class ClassB { public int? ID {get; set;} public string Name {get; set;} } 

我想使用流畅的断言来与ClassA实例进行比较。 但是我想忽略ID(因为ID将在保存后分配)。

我知道我可以这样做:

 expectedA.ShouldBeEquivalentTo(actualA, options => options.Excluding(x => x.PropertyPath == "Children[0].ID")); 

对于集合中的每个ClassB,我显然可以重复这一点。 但是,我正在寻找一种方法来排除所有ID(而不是为每个元素做一个排除)。

我已经读过这个问题但是如果我删除了[0]索引器,断言就会失败。

这可能吗?

关于什么?

 expected.ShouldBeEquivalentTo(actualA, options => options.Excluding(su => (su.RuntimeType == typeof(ClassB)) && (su.PropertyPath.EndsWith("Id")));` 

或者你可以在属性路径上进行RegEx匹配,例如

 expected.ShouldBeEquivalentTo(actualA, options => options.Excluding(su => (Regex.IsMatch ("Children\[.+\]\.ID")); 

我实际上喜欢最后一个,但正则表达式的东西让它有点难以阅读。 也许我应该使用一种方法扩展ISubjectInfo以匹配通配符模式的路径,以便您可以这样做:

 expected.ShouldBeEquivalentTo(actualA, options => options .Excluding(su => su.PathMatches("Children[*].ID"))); 

我刚刚遇到类似的问题,最新版本的FluentAssertions已经改变了一些东西。

我的对象包含其他对象的字典。 词典中的对象包含我要排除的其他对象。 我的场景是测试Json序列化,我忽略了某些属性。

这对我有用:

 gotA.ShouldBeEquivalentTo(expectedB , config => config .Excluding(ctx => ctx.SelectedMemberInfo.MemberType == typeof(Venue)) .Excluding(ctx => ctx.SelectedMemberInfo.MemberType == typeof(Exhibit)) .Excluding(ctx => ctx.SelectedMemberInfo.MemberType == typeof(Content)) .Excluding(ctx => ctx.SelectedMemberInfo.MemberType == typeof(Survey)) .Excluding(ctx => ctx.SelectedMemberInfo.MemberType == typeof(Media)) ); 

花了一些时间来研究如何做到这一点,但它真的很有用!

简单的方法是直接在集合上设置断言,并将其排除在ClassA等价断言之外:

 expectedA.ShouldBeEquivalentTo(expectedB, o => o.Excluding(s => s.PropertyInfo.Name == "Children")); expectedA.Children.ShouldBeEquivalentTo(expectedB.Children, o => o.Excluding(s => s.PropertyInfo.Name = "Id")); 

最简单的方法是:

 expected.ShouldBeEquivalentTo(actual, config => config.ExcludingMissingMembers()); 

根据Dennis Doomen回答的 RegEx匹配理念,我能够让它发挥作用

 expected.ShouldBeEquivalentTo(actualA, options => options.Excluding(su => (Regex.IsMatch(su.SelectedMemberPath, "Children\\[.+\\].ID")); 

与Dennis的区别答案:传递su.SelectedMemberPath,双反斜杠以逃避方括号。