assertEquals(obj,obj)返回失败的测试 [英] assertEquals(obj,obj) returns a failed test

查看:97
本文介绍了assertEquals(obj,obj)返回失败的测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗯,我有一个金钱对象,可以将其他金钱对象添加到其中. 我在Java中尝试了assertEquals()来测试我的代码是否还可以,但是随后失败了.

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.

我非常肯定我的代码是正确的(System.out.println返回正确的答案),我认为我只是以错误的方式使用了assertEquals. T_T

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

如果要查找myObj1 == myObj2进行测试,该怎么使用?

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;
    }
}

推荐答案

您没有在Money类中重写Object类中的equals()方法.如果是这样,则将对象通过其引用进行比较,在这种情况下,引用将有所不同. 此处,您可以找到规则用于实现equals.

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.

这篇关于assertEquals(obj,obj)返回失败的测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆