【发布时间】:2023-03-08 00:05:02
【问题描述】:
我将如何为这个 equals 方法编写一个测试用例,在它检查对象是“整数”还是“Patron”之后比较 ID 号。
方法如下:
public boolean equals(Object other) {
boolean bool = false;
if (other instanceof Patron) {
Patron patron = (Patron) other;
bool = this.idNumber == patron.idNumber;
} else if (other instanceof Integer) {
Integer id = (Integer) other;
bool = this.idNumber == id;
}
return bool;
【问题讨论】:
-
您将创建该类的各种实例,然后根据您期望的值断言
obj1.equals(obj2)是真还是假。请注意,您对Integer的处理违反了equals的关联性契约,因为patron.equals(integer)并不总是等于integer.equals(patron)。 -
一般来说,不同类别的东西不应该被认为是平等的。
-
像其他方法一样编写测试。使用某个值调用被测方法,并将返回的值与您期望的值进行比较。
equals与这里的任何其他方法没有什么不同。
标签: java oop junit equals testcase