In a recent project, for unit tests, we use NMock to simulate the behavior of the methods that are dependent on the test method. We encountered a problem when defining the parameter values and return values of the simulation method. When a parameter or return value is an object, we must override its Equals method to match the simulated value with the actual value.
Therefore, I will rewrite the Equals and GetHashCode methods for each object class.
We have such a class:
[Csharp]
Public class ShippingRequest
{
IEnumerable <string> ResourceIds;
String Explorer;
String Comment;
}
Its Equals method compares ResourceIds, referers, and Comment values. If all values are the same, true is returned.
ResourceIds is actually the ID number of a group of devices we need to mail, so we do not care about their order, as long as the two objects contain a group of identical ID numbers, they can be determined that their ResourceIds are equal.
How can we compare the ResourceIds of the set type?
Naturally, we can compare the elements in the set one by one to check whether the two sets contain the same elements.
However, if you use LINQ, we can use a very simple method.
[Csharp]
List2.Except (list1); // elements returned in list2 but not in list1
Therefore, we can write the Equals method of the ShippingRequest class as follows:
[Csharp]
Public override bool Equals (object o)
{
If (o = null |! This. GetType (). Equals (o. GetType ()))
{
Return false;
}
If (this = o)
{
Return true;
}
Var shippingRequest = o as ShippingRequest;
If (this. ResourceIds. substring T (shippingRequest. ResourceIds). Count () = 0 &&
ShippingRequest. ResourceIds. encode T (this. ResourceIds). Count () = 0 &&
This. cycler. Equals (shippingRequest. Cycler )&&
This. Comment. Equals (shippingRequest. Comment ))
{
Return true; www.2cto.com
}
Return false;
}
Then we only need to override the GetHashCode method of the ShippingRequest class to complete the entire class.
The set type mentioned here can be IEnumerable or any collection class implementing it. The type in the set can also be any type. Of course, if it is a custom class, we first need to correctly override the Equals method of the custom class.