Busy writing a unit test for a controller that produces a view-model that includes a list of options as IEnumerable < SelectListItem >. I tried checking that the expected list contains all the ones in the view-model and vice-versa. To my surprise this is always false. So I created the following test:
[TestMethod]
public void CanEqual()
{
var x = new SelectListItem {Selected = false, Text = "A", Value = "A"};
var y = new SelectListItem { Selected = false, Text = "A", Value = "A" };
Assert.AreEqual(x, y);
}
The assertion always fails but the two are equal. Does SelectListItem really not implement Equals or am I just missing something here?
Adding to Shark’s answer… As for what to do about it, other than implementing
IEquatable<T>on a derived class (and if you do that, you really should override the non-genericEquals()too – and if you do that, you really should overrideGetHashCode())… Anyway… other than doing that, you could:IEqualityComparer<T>for each of the types you need to compare.Neither will allow you to use
Assert.AreEqual(), but in general, I’m not in favor of adding code to your objects just to allow testing – prefer keeping it in the test project. Plus, with these approaches, you won’t “need” to implementGetHashCode()etc.