![](/img/trans.png)
[英]How to compare two Sets of objects Not overriding equals/hashCode with Comparator and Streams
[英]AssertionFailedError error when trying to compare two objects from the same class(after Overriding Equals() and Hashcode())
我第一次嘗試覆蓋我的類(金錢)來檢查特定屬性上的兩個對象。 第二次我試圖檢查來自同一個類(金錢)的兩個相同的對象,但它沒有用。
我嘗試覆蓋 Equals() 和 Hashcode()
在頭等艙(錢)。 在文件的頂部。
public static final Money HALF_DINAR = new Money(BigDecimal.valueOf(0.50));
public BigDecimal current_Money;
public static final Money ZERO =new Money(BigDecimal.ZERO);
public static Money mInsideMachine = new Money(BigDecimal.ZERO);
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Money)) {
return false;
}
Money money = (Money) o;
return new EqualsBuilder()
.append(this.current_Money,money.current_Money)
.isEquals();
}
@Override
/*public int hashCode() {
return Objects.hash(current_Money);
}*/
public int hashCode(){
return new HashCodeBuilder(17, 37)
.append(current_Money)
.toHashCode();
}
我用來檢查對象的命令是
assertThat(snackMachine.moneyInside()).isEqualTo(Money.HALF_DINAR);
*請注意:object 零食機來自 class 零食機,但退貨來自 Money 的 class。 這是moneyInside的代碼。
public Money moneyInside() {
return Money.mInsideMachine;
}
第二個文件的代碼(不可更改)(SnackMachine 類)單元測試
@Test
void buying_a_snack_after_inserting_just_enough_money_then_the_money_inside_should_equals_to_money_inserted() {
snackMachine.insertMoney(Money.QUARTER_DINAR);
snackMachine.insertMoney(Money.QUARTER_DINAR);
snackMachine.buySnack(SnackType.CHEWING_GUM);
System.out.println("Moneyinside (Unit test)"+Money.mInsideMachine.current_Money.toString());
System.out.println("Money half dinar (Unit test)"+Money.HALF_DINAR.current_Money.toString());
//assertThat(snackMachine.moneyInTransaction()).isEqualTo(Money.ZERO);
assertThat(snackMachine.moneyInside()).isEqualTo(Money.HALF_DINAR);
}
我添加了一些代碼來打印值,output 是:
Moneyinside (Unit test)0.50
Money half dinar (Unit test)0.5
org.opentest4j.AssertionFailedError:
Expecting:
<com.progressoft.induction.Money@885>
to be equal to:
<com.progressoft.induction.Money@311>
but was not.
Expected :com.progressoft.induction.Money@311
Actual :com.progressoft.induction.Money@885
這里的問題是 0.5 不等於 0.50 ,除非您使用isEqualByComparingTo
。 見https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html#compareTo-java.math.BigDecimal-
例子:
// assertion will pass because 8.0 is equal to 8.00 using BigDecimal.compareTo(BigDecimal)
assertThat(new BigDecimal("8.0")).isEqualByComparingTo(new BigDecimal("8.00"));
// assertion fails
assertThat(new BigDecimal("8.0")).isEqualTo(new BigDecimal("8.00"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.