mapper.readValue(json, Hello.class) return object is not equals to expected object

496 Views Asked by At

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?

2

There are 2 best solutions below

2
Vikrant Kashyap On

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.

0
stefana On

You could try to implement Comparable to allow comparing via:

expected.compareTo(actual);

or

compare(expected, actual);