Assert开发者_如何学C.AreEqual is failing on POCOs. It, however, is not failing on individual items in POCOs. How to make it work on full POCOs in VS 2010
Do your POCOs override Equals
in an appropriate way? If not, that's the problem. Override Equals
and GetHashCode
and you should be fine.
That's assuming there's only one notion of equality which you need to cover. An alternative is to implement IEqualityComparer<T>
in another class, and use that. (I don't know offhand whether Assert.AreEqual
takes an optional IEqualityComparer<T>
parameter, but you could always call it explicitly.)
you could look into the expected objects library. its very neat and handles all of your comparison logic for you behind the scenes, making your code significantly easier and slimmer. you can even tell it to ignore types, so if you want to just check a couple properties of an object, you can compare it with an object, or anything for that matter.
The tests are failing because your objects are not equal. They may have the same values in their fields, but this does not make them equal. By default objects are equal if they have the same address and so they are the same object.
To get the behaviour that you want (which is that you want objects which have properties with the same values to be equal) you need to override Equals
and define what it is that makes your objects equal. If this is all properties then check all properties here. If it is just some then only check those. Do whatever needs to be done to determine equality in your context.
If you are overriding Equals
you should also override GetHashCode
and ensure that when Equals
is true for two objects GetHashCode
return the same value for both.
精彩评论