-1

I'm comparing the two objects but the Expected object is not equal to the actual one. but they have the same values. Please provide some help.

Why ?

public testJsonToObject() {    
     Hello expected = new Hello();
     String json = "{\"id\":5,\"name\":\"Family\",\"deleteable\
 ":\"false\"}";    
     Hello actual = (Hello) mapper.readValue(json, Hello.class);
     System.out.println("Family " + actual);
     expected.setId(5);
     expected.setName("Family");
     expected.setDeleteable(false);
     System.out.println(expected);
     Assert.assertEqual(expected, actual);
  }

Simple Pojo Class Hello

public class Hello {

 private int id;
 private String name;    
 private boolean deleteable;     


  /* Getter and Setters*/

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public boolean isDeleteable() {
  return deleteable;
 }
 public void setDeleteable(boolean deleteable) {
  this.deleteable = deleteable;
 }

}

Why is this not giving me the expected result OK?

maazza
  • 7,016
  • 15
  • 63
  • 96
Shoaib Khan
  • 51
  • 1
  • 10
  • You are comparing object references instead of values. – stefana Feb 29 '16 at 10:30
  • 1
    You're relying on the `equals` implementation inherited from the `Object` class. You need to override it yourself. – JonK Feb 29 '16 at 10:30
  • Please improve the above code, @Nfear. Thank you. As i want the two object to be same after the mapper.readValue(json,Hello.class); – Shoaib Khan Feb 29 '16 at 10:46

2 Answers2

0

Try this....

if ( (expected.getId == actual.getId) && (expected.getName.equals(actual.getName))&& (expected.isDeleteable == actual.isDeleteable) ) { 
            System.out.println( "OK" );
        }

instead of...

if ( expected.equals( actual ) ) {  // Reference Checking not the value actually .
        System.out.println( "OK" );
    }

if ( expected.equals( actual ) ) Here equals method belongs to Object Class which actually checks the reference not the wrapped objects / variables values.

Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52
  • Thank you your response. But i know that both have same values. But i want to test the two objects via mapper.readvalue(json, class). as Assert.assertEqual(expected, actual) is false in this case. – Shoaib Khan Feb 29 '16 at 11:01
  • try to understand like there are two clones and both are independent from each other doesn't matter they contains the same behavior and state.. If u want to compare these objects without looking inside then try Comparable as above sugeested.. Thank you – Vikrant Kashyap Feb 29 '16 at 11:17
0

You could try to implement Comparable to allow comparing via:

expected.compareTo(actual);

or

compare(expected, actual);
stefana
  • 2,606
  • 3
  • 29
  • 47