我比较了两个对象,但是预期对象不等于实际对象。但他们有相同的价值观。请提供一些帮助。
为什么?
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);
}
简单 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;
}
}
为什么这不能给我预期的结果确定?
答案 0 :(得分:0)
试试这个......
if ( (expected.getId == actual.getId) && (expected.getName.equals(actual.getName))&& (expected.isDeleteable == actual.isDeleteable) ) {
System.out.println( "OK" );
}
而不是......
if ( expected.equals( actual ) ) { // Reference Checking not the value actually .
System.out.println( "OK" );
}
if ( expected.equals( actual ) )
此处 equals 方法属于Object Class,它实际上检查引用而不是包装的对象/变量值。
答案 1 :(得分:0)
您可以尝试实施Comparable
以允许通过以下方式进行比较:
expected.compareTo(actual);
或
compare(expected, actual);