[英]How to write a test case for an equals method
How would I go about writing a test case for this equals method that compares ID numbers after it checks if an object is an "Integer" or "Patron".在检查 object 是“整数”还是“赞助人”之后,我将如何为这个 equals 方法编写一个测试用例来比较 ID 号。
Here is the method:这是方法:
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;
If you want to verify whether the contract for the equals
and hashCode
methods is met, I would suggest using EqualsVerifier .如果您想验证是否符合equals
和hashCode
方法的约定,我建议使用EqualsVerifier 。
If you don't want to use an external library, I would suggest taking a look at it to get an idea of what (and why) you need to test.如果您不想使用外部库,我建议您查看它以了解您需要测试什么(以及为什么)。 It is a great source to learn about equals
and hashCode
.这是了解equals
和hashCode
的一个很好的来源。
It's very simple to write a test:编写一个测试非常简单:
EqualsVerifier.forClass(Foo.class).verify();
There's also a less strict alternative:还有一个不太严格的选择:
EqualsVerifier.simple()
.forClass(Foo.class).verify();
It also has several options to suppress other warnings.它还有几个选项可以抑制其他警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.