Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test two instances of object are equal JUnit [duplicate]

Tags:

java

junit

I have two objects A and B. Object A is actual result I get during JUnit test. Object B is I do a actual end db call and assume as expected review. I need to assert that two object instances A and B are equal in value and not actual object.

We have a method called assertEquals(obj expected, obj actual) in JUnit but I don't want that way.

Is there a way or workaround to achieve the same?

like image 934
thirstyladagain Avatar asked Dec 22 '14 15:12

thirstyladagain


People also ask

How do you assert two objects are equal in JUnit?

assertEquals() calls equals() on your objects, and there is no way around that. What you can do is to implement something like public boolean like(MyClass b) in your class, in which you would compare whatever you want. Then, you could check the result using assertTrue(a. like(b)) .

How do you check whether two objects are of the same instance?

If the two objects have the same values, equals() will return true . In the second comparison, equals() checks to see whether the passed object is null, or if it's typed as a different class. If it's a different class then the objects are not equal.

What does assertSame () method used for assertion?

What does assertSame() method use for assertion? Explanation: == is used to compare the objects not the content. assertSame() method compares to check if actual and expected are the same objects.

What is assertSame in JUnit?

The assertSame() method tests if two object references point to the same object. 7. void assertNotSame(object1, object2) The assertNotSame() method tests if two object references do not point to the same object.


1 Answers

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); 

Updated in 06/21 - apparently this is deprecated and has been replaced with:

assertThat(actual).usingRecursiveComparison().isEqualTo(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.

like image 126
tddmonkey Avatar answered Oct 05 '22 11:10

tddmonkey