簡體   English   中英

比較兩個List <string[]> C#單元測試中的對象

[英]Compare two List<string[]> objects in C# Unit Test

我正在嘗試創建一個比較兩個字符串數組列表的單元測試。

我嘗試創建兩個完全相同的List<string[]>對象,但是當我使用CollectionAssert.AreEqual(expected, actual); ,測試失敗:

[TestMethod]
public void TestList()
{
    List<string[]> expected = new List<string[]> {
        new string[] { "John", "Smith", "200" },
        new string[] { "John", "Doe", "-100" }
    };

    List<string[]> actual = new List<string[]> {
        new string[] { "John", "Smith", "200" },
        new string[] { "John", "Doe", "-100" }
    };

    CollectionAssert.AreEqual(expected, actual);
}

我也嘗試過Assert.IsTrue(expected.SequenceEqual(actual)); ,但那也失敗了。

如果我比較兩個字符串列表或兩個字符串數組,這兩種方法都有效,但在比較兩個字符串數組列表時它們不起作用。

我假設這些方法失敗,因為他們正在比較兩個對象引用列表而不是數組字符串值。

如何比較兩個List<string[]>對象並判斷它們是否真的相同?

CollectionAssert.AreEqual(expected, actual); 失敗,因為它比較了對象引用。 expectedactual參考不同的對象。

Assert.IsTrue(expected.SequenceEqual(actual)); 由於同樣的原因失敗了。 這次比較了expectedactual的內容,但元素本身就是不同的數組引用。

也許嘗試使用SelectMany壓縮兩個序列:

var expectedSequence = expected.SelectMany(x => x).ToList();
var actualSequence = actual.SelectMany(x => x).ToList();
CollectionAssert.AreEqual(expectedSequence, actualSequence);

由於Enigmativity在他的評論中正確注意到,當數組和/或它們的元素數量不同時,SelectMany可能會給出肯定的結果,但是對列表進行展平將導致相同數量的元素。 只有在這些數組中始終具有相同數量的數組和元素時才是安全的。

它失敗了,因為列表中的項是對象( string[] ),並且由於您沒有指定CollectionAssert.AreEqual如何比較兩個序列中的元素,因此它將回退到比較引用的默認行為。 例如,如果要將列表更改為以下內容,則會發現測試通過,因為現在兩個列表都引用了相同的數組:

var first = new string[] { "John", "Smith", "200" };
var second = new string[] { "John", "Smith", "200" };

List<string[]> expected = new List<string[]> { first, second};
List<string[]> actual = new List<string[]> { first, second};

要避免引用比較,您需要告訴CollectionAssert.AreEqual如何比較元素,您可以通過在調用它時傳入IComparer來實現:

CollectionAssert.AreEqual(expected, actual, StructuralComparisons.StructuralComparer);

最好的解決方案是檢查每個子集合中的項目以及每個相應子集合中的項目數。

試試這個:

bool equals = expected.Count == actual.Count &&
              Enumerable.Range(0, expected.Count).All(i => expected[i].Length == actual[i].Length &&
                                                           expected[i].SequenceEqual(actual[i]));
Assert.IsTrue(equals);

這將檢查:

  • 兩個列表都具有相同的長度
  • 兩個列表中的所有子集合都具有相同的長度
  • 每對子集合中的項目是相同的

注意 :使用SelectMany不是一個好主意,因為它可能會產生誤報,您在第二個列表中有相同的項目,但在不同的子集合中展開。 我的意思是,即使第二個列表在一個子集合中具有相同的項目,它也會認為兩個列表是相同的。

暫無
暫無

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

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