【问题标题】:FluentAssertions: collection subset should contain equivalent of listFluentAssertions:集合子集应包含等效的列表
【发布时间】:2022-07-17 20:20:06
【问题描述】:

我有一个收藏:

new[] { new { A = 5, PropIDontCareAbout = "XXX" }, new { A = 7, PropIDontCareAbout = "XXX" }, new { A = 9, PropIDontCareAbout = "XXX" } }

我想检查它至少包含new { A = 9 } 和new { A = 5 } 以任何顺序。

我可以使用ContainEquivalentOf,但我必须一个一个地做:

var actual = new[] { 
  new { A = 5, PropIDontCareAbout = "XXX" }, 
  new { A = 7, PropIDontCareAbout = "XXX" }, 
  new { A = 9, PropIDontCareAbout = "XXX" } 
};
var expected = new [] { new { A = 5 }, new { A = 9 } };
foreach (var expectedItem in expected) {
    actual.Should().ContainEquivalentOf(expectedItem);
}

更新:我不能使用Contains,因为它要求实际对象和预期对象具有相同的类型。

【问题讨论】:

    标签: fluent-assertions


    【解决方案1】:

    我没有看到明确的解决方案。您可以使用Select 以期望的格式创建主题,然后您可以使用 Contains(IEnumerable<T> expected, ...):

    var actual = new[] { 
        new { A = 1, PropIDontCareAbout = "XXX" }, 
        new { A = 7, PropIDontCareAbout = "XXX" }, 
        new { A = 9, PropIDontCareAbout = "XXX" } 
    };
    
    actual.Select(x => new { x.A }).Should()
        .Contain(new[] { new { A = 9 }, new { A = 5 } });
    

    如果其中一个元素不在列表中,您会收到如下消息:

    Expected collection {{ A = 1 }, { A = 7 }, { A = 9 }}
    to contain {{ A = 9 }, { A = 5 }},
    but could not find {{ A = 5 }}.
    

    【讨论】:

    • @thx-1138,如果我的回答能得到反馈,那就太好了!
    • 为迟到的反应道歉。您的解决方案不起作用,因为 Contain 进行完全匹配,而我需要进行部分对象匹配的 Equivalent 比较。我会更新我的问题。
    • 你是对的,@THX-1138。我已经通过解决方法更新了我的答案。
    猜你喜欢
    • 2012-02-17
    • 2017-12-02
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多