2014-03-03 65 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)) 
); 

花了一些時間來解決如何做到這一點,但它確實有用!

相關問題