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

标签 java null sonarqube 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.

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

关于java - 测试 equals() 时解决 SonarQube 中的 "null comparison"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50414011/

相关文章:

java - Activity 开始时android上没有自动屏幕键盘

Java SimpleDateFormat 问号而不是月份

java - Objects.requireNonNullElse() 和 Optional.ofNullable().orElse() 有什么区别?

sonarqube - 将rules.csv文件导入 Sonar

sonarqube - sonar.host.url 不适用于 sonar-maven-plugin :2. 7

java - spring security - 动态角色

java - 在列表中键入 Cast 对象

mysql - 不为空时更新字段

java - 如何告诉 Java 一个变量不可能为空?

java - 当根项目不包含任何类时,Sonar/findbugs 失败