Skip to main content

Unit Testing JAXB Objects?

4 replies [Last post]
bartspedden
Offline
Joined: 2005-05-05
Points: 0

I need to write some unit tests with junit to validate that two JAXB objects are identical. I've read that the .equals() on the JAXB object will not work here for some reason. I could write a sorter to sort the object data and then implicitly test each attribute, but that seems like the wrong approach since the JAXB object could change. I've gotten one idea of using the Jakarta EqualsBuilder but I figured I would post a question here to see how you all test your JAXB objects.

Thanks in advance,

Bart

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
skaffman
Offline
Joined: 2004-03-14
Points: 0

I had similar problem a few days ago. I thought about using the EqualsBuilder in commons lang, but the problem with that approach is it won't tell you which bit of your object graph failed the equals test.

My solution was to use the ToStringBuilder on each object, then compare the two strings. Very easy to spot the difference then :)

You need to tweak the ToStringBuilder to leave out the object identity value and format things nicely to aid testing, but it works pretty well.

kirillcool
Offline
Joined: 2004-11-17
Points: 0

You can write a simple class that uses reflection to compare two objects. Fetch all getters from both objects, say Obj1Getters and Obj2Getters, invoke them all and store the results in two sets. Now, for each entry in the first set, compare it to all entries in the second set (by class, by fields, using equals()). If you have found none - you fail. If you have found a match - remove the entries from both sets.

kohsuke
Offline
Joined: 2003-06-09
Points: 0

There's reflection based equality tester in Apache commons I think. You might want to take a look.

euxx
Offline
Joined: 2003-06-10
Points: 0

How about dumping them to xml and then use xmlunit to compare?