问题
Hmm, I have a money object that allows me to add other money objects into it.
I tried assertEquals()
in java for testing out if my code if okay, but then it failed.
I'm very positive that my code is correct (System.out.println
returns the correct answer), I think I'm just using assertEquals
in the wrong manner. T_T
What exactly do I use if I want to find out if myObj1 == myObj2
for the tests?
**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:
You didn't override equals()
method from Object class in your Money class. If so, objects are compared by their references, which are different in this case.
Here you can find rules for implementing equals
.
回答2:
You could write your tests to compare fields:
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());
来源:https://stackoverflow.com/questions/8426683/assertequalsobj-obj-returns-a-failed-test