【问题标题】:assertEquals(obj,obj) returns a failed testassertEquals(obj,obj) 返回失败的测试
【发布时间】:2011-12-08 05:41:34
【问题描述】:

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

我非常肯定我的代码是正确的(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;
    }
}

【问题讨论】:

  • 你的 Money 类的 equals 方法在哪里?
  • 另外,在compareCurrency 中,您有效地编写了if (true) return true; else if (false) return false;,您只需要:return money.currency.equals(currency);
  • 哎呀!那一定是缺少的链接.. T__T
  • 通过 equals() 我的意思是你在比较两个字符串时看到的 equals()。我使用枚举作为货币
  • 在覆盖equals时请不要忘记覆盖hashcode。

标签: java unit-testing tdd assert


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可以编写测试来比较字段:

    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());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多