java assertEquals(obj,obj)返回失败的测试
嗯,我有一个money对象,它允许我向其中添加其他money对象。
我试着用java assertEquals()
测试我的代码是否正常,但是失败了
我非常肯定我的代码是正确的(System.out.println
返回正确的答案),我认为我只是以错误的方式使用了assertEquals
。图特
如果我想知道测试是否使用myObj1 == myObj2
,我应该使用什么
**in my test.java**
assertEquals(new Money(money1.getCurrency(),new Value(22,70)),money1.add(money2));
**in my money class**
public class Money {
Currency currency;
Value value;
//constructor for Money class
public Money(Currency currency, Value value) {
super();
this.currency = currency;
this.value = value;
}
public Currency getCurrency() {
return currency;
}
public void setCurrency(Currency currency) {
this.currency = currency;
}
//must have same currency
public Money add(Money moneyToBeAdded){
Money result = new Money(moneyToBeAdded.currency, new Value(0,0));
Value totalInCents;
int tempCents;
int tempDollars;
if(compareCurrency(moneyToBeAdded)){
totalInCents = new Value(0,moneyToBeAdded.value.toCents()+value.toCents());
tempDollars = (totalInCents.toDollars().getDollar());
tempCents = (totalInCents.toDollars().getCents());
result = new Money(moneyToBeAdded.currency, new Value(tempDollars,tempCents));
System.out.println(result.value.getDollar()+"."+result.value.getCents());
}
return result;
}
private boolean compareCurrency(Money money){
return (money.currency.equals(currency))? true : false;
}
}
# 1 楼答案
您没有在Money类中重写对象类中的
equals()
方法。如果是这样,对象将通过它们的引用进行比较,在本例中,它们是不同的。 Here您可以找到实现equals
的规则# 2 楼答案
您可以编写测试来比较字段: