My first blog, hey
Assert. areequal is often used in unittest.
However, for the reference type, areequal determines whether the address is equal, rather than whether all the fields of the object are one to one equal.
Therefore, when the values are equal, we must either compare all the fields of the two objects in unittest, or rewrite the equals method to compare the fields one by one.
Either way, you must compare each field, which is troublesome.
Today, I am tired of writing and writing, so I want to find a convenient method, so I have the content of this article.
Generally, the objects we want to compare are all self-defined entity/model, which contains a large number of properties of serializable.
If you mark this entity as serializable, use xmlserializer to serialize the object and compare the innerxml of the two xmldocuments after serialization.
In this way, you do not need to change the code if you add or remove fields in the future.
Add the debug tag and use it in the test phase without affecting the performance and logic of the actual environment.
If referenceequals is required in some places in the program
You can put that piece of code in the unittest project as tools instead of rewriting equals.
The Code is as follows. I wonder if you have any other good solutions.
1 [serializable]
2 public abstract class entitybase
3 {
4 # If debug
5 Public override bool equals (object right)
6 {
7 if (Right = NULL)
8 return false;
9 If (object. referenceequals (this, right ))
10 return true;
11 if (this. GetType ()! = Right. GetType ())
12 Return false;
13
14 xmldocument leftxml = serialize (this );
15 xmldocument rightxml = serialize (right );
16
17 return leftxml. innerxml = rightxml. innerxml;
18}
19
20 private xmldocument serialize (Object OBJ)
21 {
22 using (memorystream stream = new memorystream ())
23 {
24 xmldocument Doc = new xmldocument ();
25 xmlserializer serializer = new xmlserializer (obj. GetType ());
26 serializer. serialize (stream, OBJ );
27 stream. Seek (0, seekorigin. Begin );
28 Doc. Load (Stream );
29
30 return Doc;
31}
32}
33
34 public override int gethashcode ()
35 {
36 return base. gethashcode ();
37}
38 # endif
39}