@EqualsAndHashCode(callSuper = true)单测如何覆盖,代码示例
时间: 2023-11-01 13:51:29 浏览: 210
在单元测试中,覆盖带有`@EqualsAndHashCode(callSuper = true)`注解的方法,可以通过继承父类并重写该方法来实现。下面是一个示例代码:
```java
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ParentClass {
private final int id;
private final String name;
public ParentClass(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ParentClass that = (ParentClass) o;
if (id != that.id) return false;
return name != null ? name.equals(that.name) : that.name == null;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
}
class ChildClass extends ParentClass {
private final String additionalProperty;
public ChildClass(int id, String name, String additionalProperty) {
super(id, name);
this.additionalProperty = additionalProperty;
}
// 覆盖父类的equals方法
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!super.equals(o)) return false;
if (o == null || getClass() != o.getClass()) return false;
ChildClass that = (ChildClass) o;
return additionalProperty != null ? additionalProperty.equals(that.additionalProperty) : that.additionalProperty == null;
}
// 覆盖父类的hashCode方法
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (additionalProperty != null ? additionalProperty.hashCode() : 0);
return result;
}
}
class ChildClassTest {
@Test
void testEqualsAndHashCode() {
ParentClass parent1 = new ParentClass(1, "Parent");
ParentClass parent2 = new ParentClass(1, "Parent");
ChildClass child1 = new ChildClass(2, "Child", "Additional");
ChildClass child2 = new ChildClass(2, "Child", "Additional");
assertEquals(parent1, parent2);
assertNotEquals(parent1, child1);
assertNotEquals(parent1.hashCode(), child1.hashCode());
assertEquals(child1, child2);
assertNotEquals(child1, parent1);
assertNotEquals(child1.hashCode(), parent1.hashCode());
// 其他针对equals和hashCode的测试
}
}
```
在上面的示例中,`ParentClass`是一个基类,其中包含了带有`@EqualsAndHashCode(callSuper = true)`注解的`equals`和`hashCode`方法。`ChildClass`继承自`ParentClass`,并重写了这两个方法以适应子类的特定需求。在`ChildClassTest`中,我们可以进行针对`equals`和`hashCode`方法的单元测试。
阅读全文