Sonarkube在我的质量代码报告中给了我一个主要缺陷:
删除对“equals”的调用;与空值的比较始终返回false;请考虑使用“==null”检查空值。
然而,这
equals
调用是重写的,这意味着我要测试如果我的对象在
equals()
方法。
有没有解决这个问题的方法?我应该不测试对象的可空性,还是别无选择,只能忽略此情况?
编辑
注释中要求的代码:
对象本身:
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MyTestedObject other = (MyTestedObject) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (type != other.type)
return false;
return true;
}
在测试中:
@Test
public void test() {
MyTestedObject testedObject = new MyTestedObject();
boolean nullValue = testedObject.equals(null);
Assert.assertFalse(nullValue);
}