assertEquals()
来测试我的代码是否合适,但后来失败了。
我非常肯定我的代码是正确的(System.out.println
返回正确的答案),我想我只是以错误的方式使用assertEquals
。 T_T
如果我想知道测试是否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;
}
}
答案 0 :(得分:8)
您没有从Money类中的Object类重写equals()
方法。如果是这样,则通过它们的引用来比较对象,在这种情况下它们是不同的。
Here您可以找到实施equals
的规则。
答案 1 :(得分:1)
您可以编写测试来比较字段:
Money m1 = new Money(money1.getCurrency(),new Value(22,70));
Money m2 = new Money(money1.getCurrency(),new Value(22,70)).add(money2);
assertEquals("currencies differ", m1.getCurrency(), m2.getCurrency());
assertEquals("values differ", m1.getValue(), m2.getValue());