【发布时间】:2011-12-08 05:41:34
【问题描述】:
嗯,我有一个货币对象,允许我将其他货币对象添加到其中。
我在 java 中尝试了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;
}
}
【问题讨论】:
-
你的 Money 类的
equals方法在哪里? -
另外,在
compareCurrency中,您有效地编写了if (true) return true; else if (false) return false;,您只需要:return money.currency.equals(currency); -
哎呀!那一定是缺少的链接.. T__T
-
通过 equals() 我的意思是你在比较两个字符串时看到的 equals()。我使用枚举作为货币
-
在覆盖equals时请不要忘记覆盖hashcode。
标签: java unit-testing tdd assert