【问题标题】:Fluent assertions and comparison of List<List<string>>List<List<string>> 的流利断言和比较
【发布时间】:2017-09-20 04:10:34
【问题描述】:

我在使用 Fluent Assertions 比较两个 List&lt;List&lt;string&gt;&gt; 类型的集合时遇到问题。使用 Should().Equal() 方法时(顺序很重要),我收到以下(神秘的 ;-) 消息:

Expected collection to be equal to {{"Telefoonnummer"}, {"E-mailadres"}, {"E-mailadres controle"}}, but {{"Telefoonnummer"}, {"E-mailadres"}, {"E-mailadres controle"}} differs at index 0.

因此,对象看起来是相等的。此外,在调试对象时似乎完全相同。比较两个List&lt;string&gt; 对象时,测试通过,没有问题,但与List&lt;List&lt;string&gt;&gt; 相同的测试失败。我使用了错误的断言方法吗?还是 Fluent Assertions 不能正确处理这种类型的集合?

【问题讨论】:

    标签: c# fluent-assertions


    【解决方案1】:

    用actualList.ShouldBeEquivalentTo(expectedList. config =&gt; config.WithStrictOrder());代替Should().Equal()

    ShouldBeEquivalentTo 方法将检查两个列表是否包含具有相同值的项目。如果列表包含引用类型的实例,它将比较这些实例的完整对象图。添加为第二个参数
    config =&gt; config.WithStrictOrdering() 将检查项目的顺序是否与预期列表中的相同。

    另一方面,Should().Equal() 将使用“标准”相等检查,其中 var listOne = new List&lt;string&gt; { "test" }; 和 var listTwo = new List&lt;string&gt; { "test" }; 将是不同的实例。

    【讨论】:

    • 谢谢!这就是我一直在寻找的东西,就像一个魅力。
    【解决方案2】:

    在使用 == 比较 string 时检查值是否相等,List&lt;string&gt; 检查列表的地址。这意味着包含相同元素的两个列表不相同,因为您正在比较列表的地址而不是里面的项目。举个例子:

    List<string> listA = new List<string> { "item" };
    List<string> listB = new List<string> { "item" };
    bool equal = listA == listB; //equal will be false
    

    要解决您的问题,您可以结合 SelectMany 和 SequenceEqual 来比较列表中的项目。这是一个小例子:

    List<List<string>> listToCompare = new List<List<string>>()
    {
        new List<string> {"first", "second"},
        new List<string> {"third"}
    };
    List<string> expectedList = new List<string> { "first", "second", "third" };
    bool sequenceEqual = listToCompare.SelectMany(i => i).SequenceEqual(expectedList); //sequenceEqual will be true
    

    【讨论】:

    • 感谢您的回答,我没有意识到这一点!现在我正在重新考虑是否需要List&lt;List&lt;string&gt;&gt;,也许List&lt;string&gt; 就足够了。当然,当您的示例中的 expectedList 已经属于该类型时。
    • 或者可以比较两个List&lt;List&lt;string&gt;&gt;类型的对象吗?
    • 虽然字符串是值类型 - string 是引用类型,Reference.Equals(firstStringWithWordTest, secondStringWithWordTest) - 将返回 false,因为两个参数是不同的实例。但firstStringWithWordTest == secondStringWithWordTest 将返回 true,因为字符串相等性检查值相等性。
    • 完全正确@Fabio ...这有点不走运...我已经更正了。谢谢!
    • @jvanderwoude 是的,与List&lt;List&lt;string&gt;&gt; 相比,nestedListA.SelectMany(i =&gt; i).SequenceEqual(nestedListB.SelectMany(i =&gt; i)); 是可能的
    猜你喜欢
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 2011-12-11
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 2018-01-06
    相关资源
    最近更新 更多