List <list <string>&gt;的流畅断言和比较

时间:2017-04-23 13:30:28

标签: c# fluent-assertions

使用Fluent Assertions比较两个类型List<List<string>>的集合时遇到问题。当使用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<string>对象时没有问题,但是List<List<string>>的相同测试失败了。我使用错误的断言方法吗?或者Fluent Assertions没有正确处理这种类型的集合吗?

2 个答案:

答案 0 :(得分:0)

在使用string检查值相等的==进行比较时,List<string>会检查列表的地址。这意味着包含相同元素的两个列表不相同,因为您要比较列表的地址而不是内部的项目。让我们举个例子:

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

要解决您的问题,您可以将SelectManySequenceEqual结合使用,以比较列表中的项目。这是一个小例子:

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

答案 1 :(得分:0)

而不是Should().Equal()使用actualList.ShouldBeEquivalentTo(expectedList. config => config.WithStrictOrder());

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

另一方面,

Should().Equal()将使用&#34;标准&#34;等同性检查,其中var listOne = new List<string> { "test" };var listTwo = new List<string> { "test" };将是不同的实例。

相关问题