测试 equals() 时解决 SonarQube 中的 "null comparison" 错误

Resolving "null comparison" bug in SonarQube while testing equals()

SonarQube 在我的质量代码报告中抛出一个主要错误:

Remove this call to "equals"; comparisons against null always return false; consider using '== null' to check for nullity.

但是,此 equals 调用是一个覆盖调用,这意味着我想测试如果我的对象在 equals() 方法中实际上为 null 会发生什么。

这个问题有解决办法吗?我是不是应该测试对象的可空性,还是除了忽略这种情况别无选择?


编辑评论中要求的代码:

对象本身:

@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);
}

SonarQube 告诉您您的代码中有错误。如果在 java spec 中定义明确,则 equals 的合同:

For any non-null reference value x, x.equals(null) should return false.

如果您在覆盖中的做法不同 - 您做错了。