2014-03-03 26 views
19

我有两个类:如何使用排除在FluentAssertions集合中的属性?

public class ClassA 
{ 
    public int? ID {get; set;} 
    public IEnumerable<ClassB> 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(而不是对每个元素进行排除)。

我读过this question但是,如果我删除[0]索引器断言失败。

这可能吗?

回答

19

怎么样?

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

或者你可以做财产路径上的正则表达式匹配,如

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

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

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

我打算将这一个标记为答案,因为扩展方法中的正则表达式是我最后使用的方法 – Liath

+2

在更新版本的FluentAssertions中,这有何变化?我不确定'PropertyPath'仍然存在 – superjos

5

简单的办法是设置收集断言直接,以其对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")); 
15

我刚刚碰到过类似的问题,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)) 
); 

花了一些时间来解决如何做到这一点,但它确实有用!

相关问题