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

查看:41
本文介绍了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天全站免登陆