I'm using Java 8, Netbeans 8.2 and JUnit 4.12.
I have two instances of a class that I want to compare to know if they are "equal", where their properties have the same values. That is, if they have id and name, if I write in the test:
assertEquals(instanceA.getId(), instanceB.getId( ));
assertEquals(instanceA.getName(), instanceB.getName( ));
OK, but if I add a third assert by comparing them directly:
assertEquals(instanceA, instanceB);
or
assertTrue(instanceA.equals(instanceB));
this fails. I think because although they keep the same thing they are different instances (they point to different memory addresses). Can someone clarify it? Thanks.
Edited
The question suggested as "duplicate" focuses on comparing the value of two Strings and all the answers go in this direction, except this one: link that makes a comparison of objects, ignoring this answer, all other solutions fail. My question refers to how to compare objects according to the value of their properties and specifically in order to implement unit tests. I think that by looking at both questions and their answers you can see similarities but it is clear that they are two different questions.
Maybe he does not explain me correctly. If someone is unclear, is it the same question as it has a completely different solution?
Compare two strings:
String a = "hola";
String b = "hola";
boolean res = a.equals(b);
System.out.println("Comparando strings: " + res);
// Comparando strings: true
Compare two objects:
class Foo {
private int id;
private String name;
public Foo(int id, String name) {
this.id = id;
this.name = name;
}
} // class
Foo a = new Foo(1, "hola");
Foo b = new Foo(1, "hola");
boolean res = a.equals(b);
System.out.println("Comparando objetos: " + res);
// Comparando objetos: false
What happened? Well that's what I was basically asking ...