Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

java - Test two instances of object are equal JUnit


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Think about exactly what it is you're trying to achieve. Do you want to test object identity or verify that the two objects have exactly the same data? From your suggestion of assertEquals I am guessing you want to go field-by-field.

If the objects are shallow you can use

assertThat(actual, samePropertyValuesAs(expected));

This fails when the object is a composite though. If you want to walk the entire graph you can use the sameBeanAs matcher we wrote some time back to address this issue:

assertThat(actual, sameBeanAs(expected));

If you're using AssertJ then you can also use the built-in functionality like this:

assertThat(actual).isEqualToComparingFieldByField(expected);

One thing you don't want to do it override the equals method for this as that might change in the future to accommodate business need.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...