Is MVC SelectListItem not equal?

It is busy writing a unit test for a controller that creates a view model that includes a list of parameters in the form IEnumerable <SelectListItem>. I tried to verify that the expected list contains all those contained 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); } 

An assertion always fails, but they are equal. Does SelectListItem really not implement Equals or am I just missing something here?

+4
source share
2 answers

Adding Shark to the answer ... As for what to do with it, other than implementing IEquatable<T> in the derived class (and if you do, you really need to override the non-generic Equals() ), and if you do, you really should override GetHashCode() ) ... Anyway ... apart from this, you could:

  • Create a helper method in the test project to compare the values ​​(you can write a common goal using Reflection, which will work for most simple classes) or
  • Create a helper class that implements IEqualityComparer<T> for each of the types you need to compare.

None of them will allow you to use Assert.AreEqual() , but in general I am not a supporter of adding code to your objects to allow testing - prefer to store it in a test project. In addition, with these approaches you will not need to implement GetHashCode() , etc.

+2
source

This is because by default it tests the same link. In this case, you have two instances of the object, so they are not "equal."

If you want to change this behavior, you just need to implement the IEquatable<T> interface, and you can override what Equals() will return. For instance:

 public bool Equals(YourClass other) { return (this.Value == other.Value); } 

For a good reference to Object.Equals() see this link on MSDN . Equality for reference types is based on their reference. That is, if they do not refer to the same object, then Equals() will return false .

+2
source

Source: https://habr.com/ru/post/1394516/


All Articles