Home > Enterprise >  How do I compare objects that are arrays when I don't know what the array type is?
How do I compare objects that are arrays when I don't know what the array type is?

Time:01-18

I'm writing some unit tests. I have several data rows:

[TestMethod]
[DataRow(new int[] { 1, 2, 3 })]
[DataRow(new double[] { 1.0, 2.0, 3.0 })]
[DataRow(new string[] { "foo", "bar", "baz" })]

And the test method is essentially:

public void TestOfArrayTypes(object expected) {
  var actual = fn(expected);

  Assert.AreEqual(expected, actual);
}

My problem is the comparison. Both variables are object. I know they're both going to be arrays. The assertion fails because while they are both arrays, even of the same type and same elements, they aren't the same array reference.

That's expected, just how do I make an assertion here work that validates they are the same type, length, and elements?

I've also tried:

Assert.IsTrue(expected.Equals(actual));

And unfortunately, SequenceEqual isn't available on object, but I don't know how to cast object to some generic array type.

CodePudding user response:

Assuming you are using MsTest, then you can use CollectionAssert and cast to ICollection:

[TestMethod]
[DataRow(new [] { 1, 2, 3 },new [] { 1, 2, 3 })]
[DataRow(new [] { 1.0, 2.0, 3.0 }, new [] { 1.0, 2.0, 3.0 })]
[DataRow(new [] { "foo", "bar", "baz" }, new object[] {new [] { "foo", "bar", "baz" }})]
public void TestMethod2(object array, object array2)
{
    CollectionAssert.AreEqual(array as ICollection, array2 as ICollection);
}

Or change the test method parameter type to ICollection.

  •  Tags:  
  • c#
  • Related