assertEquals(obj,obj)返回失败的测试

황현정*_*황현정 0 java tdd unit-testing assert

嗯,我有一个货币对象,允许我添加其他货币对象.我尝试assertEquals()在java中测试我的代码是否正常,但后来失败了.

我非常肯定我的代码是正确的(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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Art*_*tem 8

您没有覆盖equals()Money类中Object类的方法.如果是这样,则通过它们的引用来比较对象,在这种情况下它们是不同的. 在这里您可以找到实施规则equals.