尝试比较同一类中的两个对象时出现断言失败错误(在覆盖 Equals() 和 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);

*请注意:对象零食机来自零食机类,但返回来自金钱类。 这是钱里面的代码。

public Money moneyInside() {
return Money.mInsideMachine;
}

第二个文件的代码(不可更改((零食机类( 单元测试

@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);
}

我添加了一些代码来打印值,输出为:

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"));

相关内容

最新更新