gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:28:26 28 4
gpt4 key购买 nike

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 的契约(Contract):

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com