我有一个银行账户的Java类示例:
public class Account {
private Integer accountNumber;
private Integer authPin;
private Integer transactionPin;
public Account(Integer accountNumber, Integer authPin, Integer transactionPin) {
this.accountNumber = accountNumber;
this.authPin = authPin;
this.transactionPin = transactionPin;
}
public Integer getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(Integer accountNumber) {
this.accountNumber = accountNumber;
}
public Integer getAuthPin() {
return authPin;
}
public void setAuthPin(Integer authPin) {
this.authPin = authPin;
}
public Integer getTransactionPin() {
return transactionPin;
}
public void setTransactionPin(Integer transactionPin) {
this.transactionPin = transactionPin;
}
@Override
public String toString() {
return accountNumber + "," + authPin + "," + transactionPin;
}
@Override
public boolean equals(Object obj) {
Account account = (Account) obj;
return (this.accountNumber == account.getAccountNumber() && this.authPin == account.getAuthPin()
&& this.transactionPin == account.getTransactionPin());
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return Objects.hashCode(this.getAccountNumber());
}
}
从代码片段中可以看出,我已经覆盖了equals()和hashCode()方法。但是当我尝试使用jUnit进行简单的断言检查时,它失败了:
public class TestFileIO {
Account account;
@Before
public void setUp() throws Exception {
account = new Account(7, 2708, 2708);
}
@Test
public void testReadTransactionFile() {
assertEquals(account, new Account(7, 2708, 2708));
}
我错过了一些重要的事情吗?
答案 0 :(得分:1)
而不是比较Integer
对象引用:
return (this.accountNumber == account.getAccountNumber() && this.authPin == account.getAuthPin() && this.transactionPin == account.getTransactionPin());
因为,Integer
对象引用不等于,例如此断言失败:
// different identities -> this assertion fails
assert new Integer(7) == new Integer(7);
使用.equals
:
return (Objects.equals(this.accountNumber, account.getAccountNumber())
&& Objects.equals(this.authPin, account.getAuthPin())
&& Objects.equals(this.transactionPin, account.getTransactionPin()));
如果保证字段永远不会是null
,则将其类型更改为int
:
private int accountNumber;
private int authPin;
private int transactionPin;
然后您不需要更改equals
实现,就像它一样。