简体   繁体   中英

Which way is better/proper to compare to objects?

I'm writing tests for testing REST services using specflow. The subject of the test is checking whether the list I get from the service contains the proper objects.

I have sample data in the background section which is put into the database at every run and it will be cleaned up after every run. The point is that I know the exact data in the database and the objects should be compared are DTO classes.

There is a point in my test where I have to compare both the result of request calling (deserialized JSON string to List<DTOObject> ) the REST service url and the test data (populated List<DTOObject> ). So, I have two List<DTOObject> . The question is that which way is better to compare them?

A, I write a generic comparator class (I don't want dependency between my test libraries and the application), and the steps are

  • passing through a method name (eg partner name)
  • get an item from either list and invoke the method to have concrete data to find the same object in the other object list
  • having concrete data looping through the another set and call the given method on every object in the list and compare the result I got in the previous step
  • if the desired class is found than compare them using the equals method

B,

  • take an item from either list
  • looping through the another list and compare every item to the item I got in the previous step using equals method

At the moment I have this two idea how to do it. I already read a few articles about comparing and I don't want to make it more complex than it is needed. I mean, implementing IComparable interface, overwriting GetHashCode method. On the other hand, I'm not sure it would be good if the DTO class implement an interface for testing sake.

Maybe I haven't read enough or I'm too close to the problem. What I would like to ask you is review my two possible approach - I'm definitely not sure they are correct - and if you know an article about this issue please share with me. I do not need existing solutions - using other's code brainlessly is not my way -, I need hints where to go.

Articles:

Thanks for your help in advance!

For comparing the Objects themselves you should overwrite the Equals() method. Overwrite GetHashCode() too if there is even the slightest chance that at some point of time your object might be used as a key in a Dictionary or something like that.

You can then use Enumerable.SequenceEqual() to check for the equality of the two lists. Instead of implemeting Equals on the object you could also create an IEqualityComparer<DTOObject> and pass it to the SequenceEqual call, but I think implementing Equals is the more versatile approach.

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