To compare two lists specifically, TestNG's Assert class has a method known as assertEquals(Object actual, Object expected) and there is an extended version of this method with customized message as assertEquals(Object actual, Object expected, String message). if the elements of the lists are in the same order.
Using Enumerable. To determine if two lists are equal, where frequency and relative order of the respective elements doesn't matter, use the Enumerable. All method. It returns true if every element of the source sequence satisfy the specified predicate; false, otherwise.
Assert. AreEqual() compares references. Usually when comparing lists I compare the count of the items and than some properties of one exact item in the list or directly the item in the list (but again it is the reference).
To make assertions about collections, you should use CollectionAssert
:
CollectionAssert.AreEqual(expected, actual);
List<T>
doesn't override Equals
, so if Assert.AreEqual
just calls Equals
, it will end up using reference equality.
I guess this will help
Assert.IsTrue(expected.SequenceEqual(actual));
If you want to check that each contains the same collection of values then you should use:
CollectionAssert.AreEquivalent(expected, actual);
Edit:
"Two collections are equivalent if they have the same elements in the same quantity, but in any order. Elements are equal if their values are equal, not if they refer to the same object." - https://msdn.microsoft.com/en-us/library/ms243779.aspx
I tried the other answers in this thread, and they didn't work for me and I was comparing collections of objects that had the same values stored in their properties, but the objects were different.
Method Call :
CompareIEnumerable(to, emailDeserialized.ToIndividual,
(x, y) => x.ToName == y.ToName && x.ToEmailAddress == y.ToEmailAddress);
Method for comparisons:
private static void CompareIEnumerable<T>(IEnumerable<T> one, IEnumerable<T> two, Func<T, T, bool> comparisonFunction)
{
var oneArray = one as T[] ?? one.ToArray();
var twoArray = two as T[] ?? two.ToArray();
if (oneArray.Length != twoArray.Length)
{
Assert.Fail("Collections are not same length");
}
for (int i = 0; i < oneArray.Length; i++)
{
var isEqual = comparisonFunction(oneArray[i], twoArray[i]);
Assert.IsTrue(isEqual);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With