Assert.AreEqual not working properly for Arrays#

As you might know, Visual Studio 2005 Team Test Edition will feature testing tools to perform unit testing, load testing, functional testing, ... It's great to see Microsoft really getting serious about providing these much-needed tools where third parties such as NUnit have been filling the gap all these years.

Anyway, while implementing some unit tests with the Release Candidate earlier today, I noticed that the following test failed:

string[] list1 = new string[] {"Test"};
string[] list2 = new string[] {"Test"};
Assert.AreEqual<string[]>(list1, list2);

After some digging, it appears that the AreEqual method doesn't special case for arrays, it just performs an Object.Equals(list1, list2). In turn, this will result in list1.Equals(list2) and I would expect the equality check for arrays to actually compare the array contents (object equality) in stead of checking if they're the same object (object identity). Especially since there is an Assert.AreSame method which should serve the latter purpose. In fact, I can understand that AreEqual would call Object.Equals and AreSame calls Object.ReferenceEquals, but I figured that System.Array would have overridden the Equals method to perform the equality check. Apparently, I was wrong.

So I had to revert to a manual check to see if both arrays have the same length and contents:

Assert.AreEqual(list1.Length, list2.Length);
for(int i = 0; i < list1.Length; i++)
{
  Assert.AreEqual(list1[i], list2[i]);
}

NUnit has worked around this problem by putting similar logic into the Assert.AreEqual method, which makes more sense in my mind.

Thursday, December 01, 2005 4:21:32 PM (Romance Standard Time, UTC+01:00)
For single and multi-dimensional arrays, as well as for any ICollection, VS Team Test provides the CollectionAssert class. In your case you can just do:

CollectionAssert.AreEqual(list1, list2);
Thursday, December 01, 2005 9:47:02 PM (Romance Standard Time, UTC+01:00)
So they thought about it after all :-) Thanks for that great tip!
Comments are closed.
All content © 2012, Jelle Druyts
On this page

Recent Photos
www.flickr.com
This is a Flickr badge showing public photos from Jelle Druyts. Make your own badge here.
Advertising
Top Picks
Statistics
Total Posts: 350
This Year: 0
This Month: 0
This Week: 0
Comments: 530
Archives
Sitemap
Disclaimer
This is my personal website, not my boss', not my mother's, and certainly not the pope's. My personal opinions may be irrelevant, inaccurate, boring or even plain wrong, I'm sorry if that makes you feel uncomfortable. But then again, you don't have to read them, I just hope you'll find something interesting here now and then. I'll certainly do my best. But if you don't like it, go read the pope's blog. I'm sure it's fascinating.

Powered by:
newtelligence dasBlog 2.0.7226.0

Sign In