Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

java - assertEquals(obj,obj) returns a failed test

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;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...