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?
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)) .
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 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With