Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to create a Unit Test that compares two lists of string arrays.

I tried creating two of the exact same List<string[]> objects, but when I use CollectionAssert.AreEqual(expected, actual);, the test fails:

[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);
}

I've also tried Assert.IsTrue(expected.SequenceEqual(actual));, but that fails as well.

Both these methods work if I am comparing two Lists of strings or two arrays of strings, but they do not work when comparing two Lists of arrays of strings.

I'm assuming these methods are failing because they are comparing two Lists of object references instead of the array string values.

How can I compare the two List<string[]> objects and tell if they are really the same?

like image 362
Tot Zam Avatar asked Dec 31 '25 15:12

Tot Zam


1 Answers

It is failing because the items in your list are objects (string[]) and since you did not specify how CollectionAssert.AreEqual should compare the elements in the two sequences it is falling back to the default behavior which is to compare references. If you were to change your lists to the following, for example, you would find that the test passes because now both lists are referencing the same arrays:

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};

To avoid referential comparisons you need to tell CollectionAssert.AreEqual how to compare the elements, you can do that by passing in an IComparer when you call it:

CollectionAssert.AreEqual(expected, actual, StructuralComparisons.StructuralComparer);
like image 85
Jason Boyd Avatar answered Jan 03 '26 05:01

Jason Boyd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!