How can I get NUnit to be more specific, which fields do not match when comparing objects?

I have 2 objects (one hand created, which is my expected, and the other from the database), and I try to make them equal. Not like in the fact that they are the same link, but that the data inside them is the same.

I use Assert.AreEqual() , but I get only general error messages such as.

 Expected: <Namespace.ObjectFoo> But was: <Namespace.ObjectFoo> 

How can I continue to show which properties do not match?

+4
source share
5 answers

Add a .ToString() override to the Namespace.ObjectFoo class that describes the contents of the object. <Namespace.ObjectFoo> is the result of the implementation of .ToString() defined on System.Object .

+3
source

You can override Equals to use Asser.AreEqual. Or compare each property one by one.

+3
source

I assume that you have redefined Equals / made the Equatable class so that you can actually get equality, even if the instances are different. Why not debug your test and see where equality fails in your Equals implementation?

+1
source

If objectFoo implements icomparable and puts the comparison logic in the CompareTo method, if you want to compare more accurate grain testing, just write a test for each property.

One of the basic concepts of unit testing is to check only one thing at a time, if you have 2 complex objects, you must compare each individuality of the properties if you do not want your class to be comparable.

+1
source

Not sure how you compare the * content * of these two objects with Assert.AreEqual() . I think you need to introduce some Compare method into your mock object, which iterates over the fields of both and accumulates, even in some string fields, the contents of which do not match. You can implement IComparable , override Equals , implement your own method, or something else.

After executing this Compare method, you will have a string with a report about the data in the format you want about fields where the equality comparison failed, if any.

+1
source

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


All Articles