簡體   English   中英

流利的斷言和List的比較 <List<string> &gt;

[英]Fluent assertions and comparison of List<List<string>>

我在使用Fluent斷言來比較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斷言不能正確處理這種類型的收集?

當使用==比較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

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

ShouldBeEquivalentTo方法將檢查兩個列表是否包含具有相同值的項目。 如果list包含引用類型的實例,它將比較那些實例的完整對象圖。 添加為第二個參數
config => config.WithStrictOrdering()將檢查項目順序與期望列表中的順序相同。

另一方面, Should().Equal()將使用“標准”相等性檢查,其中var listOne = new List<string> { "test" }; var listTwo = new List<string> { "test" }; 將是不同的實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM