简体   繁体   中英

How can I get NUnit to be more specific about which fields don't match when comparing objects?

I have 2 objects (one hand crafted that is my expected and one is coming from the database) and I'm trying to ensure they are equal. Not as in that they are the same reference but that the data within them matches.

I'm using Assert.AreEqual() but only get generic error messages such as.

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

How can I drill to further to display which properties don't match?

Add a .ToString() override on the Namespace.ObjectFoo class that describes the object's contents. The <Namespace.ObjectFoo> is the output from the implementation of .ToString() defined on System.Object .

You can override Equals so that Asser.AreEqual uses it. Or compare each property one after another.

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

Have objectFoo implement icomparable and place the comparison logic in the CompareTo method, if you want more fine grain testing comparison then simply write a test for each property.

One of the core concepts of unit testing is to only test one thing at a time, if you have 2 complex objects you should compare each property individuality unless you want your class to be comparable.

Not very sure how you gonna compare* content * of those 2 objects with Assert.AreEqual() . I think you need to introduce in your mock object some Compare method which iterates over the fields of both and accumulates, let's say in some string the fields whom content doesn't match. You can implement IComparable , override Equals , implement a custom method or whatever else.

After execution of that Compare method you will have a string with data report in format you want about fields where equality comparison failed, if there is any.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM