Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assertEquals() on two objects

Tags:

java

junit

When comparing two objects using assertEquals() does it considering looking into the internal structure viz. the properties of the objects?

Suppose I have a class A like following:

public class A {
    private int ID;
    private String name;
    private String address;
}

And suppose the supplied object's (that is to be compared to an object of A) properties are in a different order, then what will assertEquals() do? Is there a robust method to do it the other way?

like image 314
S. P Avatar asked Sep 02 '26 07:09

S. P


1 Answers

@JimGarrison is quite right - assertEquals() will just call the equals() method on your objects to determine equality.

To answer your question, "Is there a robust method to do it the other way?", if you can't properly implement the equals() method on your class for whatever reason, and you want to evaluate the equality of objects based on the values of their fields, consider using EqualsBuilder's reflectionEquals() method. It is fairly robust, and allows you to exclude whatever fields you want.

To answer your other question, "suppose the supplied object's properties are in a different order, then what will assertEquals() do?", all it will do is call the equals() method on the other instance. For example, if you call assertEquals(a, b), then that will eventually call a.equals(b). However, if you call assertEquals(b, a), then that will eventually call b.equals(a).

I hope that helps.

like image 105
entpnerd Avatar answered Sep 04 '26 19:09

entpnerd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!