【问题标题】:JUnit Testing: It throws 2 exceptionsJUnit 测试:它抛出 2 个异常
【发布时间】:2015-03-20 10:56:05
【问题描述】:

这是我需要测试的课程:

package testing;

public class Money {

    private int Amount;
    private String Currency;

    public int getAmount(){return Amount;}

    public String getCurrency(){return Currency;}

    public Money(int amount, String currency){
        Amount= amount;
        Currency= currency;
        }

    public Money addMoney(Money m){

        return (new Money(getAmount()+m.getAmount(),getCurrency()));
    }

这是我的 JUnit 测试类

package testing;

import static org.junit.Assert.*;

import org.junit.Test;

public class MoneyTest {

    @Test
    public void testAddMoney() {
        Money m1 = new Money (20,"DH");
        Money m2 = new Money(10,"DH");
        Money expected = new Money(30,"DH");
        Money result = m1.addMoney(m2);
        assertTrue(result.equals(expected));
    }


    @Test
    public void testEquals(){
        Money m1 = new Money (20,"DH");
        Money m2 = new Money(10,"DH");

        assertTrue(!(m1.equals(null)));
        assertEquals(m1, m1);
        assertEquals(m1, new Money(20,"DH"));
        assertTrue(!m1.equals(m2));


    }

当我运行测试时,它会抛出第一个异常:

 java.lang.AssertionError 
at testing.MoneyTest.testAddMoney(MoneyTest.jaba:15)15 is the number of line : assertTrue(result.equals(expected));

第二个:

java.lang.AssertionError at testing.MoneyTest.testEquals(MoneyTest.java:26) 26 is the number of line: assertEquals(m1, new Money(20,"DH"));

有什么问题???

【问题讨论】:

  • 你还没有覆盖Money中的等于...

标签: java unit-testing testing junit


【解决方案1】:

你的 Money 类没有覆盖 equals 方法,所以

assertTrue(result.equals(expected));

使用Object类的equals方法,2个实例不等于。

要么覆盖 Money 类的 equals 方法,要么更改测试

assertEquals(expected.getAmount(), result.getAmount());

【讨论】:

    【解决方案2】:

    您有两个对象,expectedresult。你知道如果金额和货币相同,这些是相等的,但程序如何知道这一点?想象一个带有namedob 字段的Person 类。两个同名同日出生的人必须用不同的Person对象表示。

    您的相等规则必须编码在 Money.equals 方法中,该方法将覆盖默认的 Object.equals 方法。

    更进一步,您可能希望Money 通过添加compareTo 方法来实现Comparable 接口。然后你就可以以自然的方式对Money 对象进行排序了。

    【讨论】:

    • 感谢您的回答
    【解决方案3】:

    补充一点,对象是由 jvm 使用哈希码识别的! Person 类可以有许多具有不同哈希码的实例。覆盖 Object 类的 equals() 时,最好覆盖 Object 类的 hashcode()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-22
      • 1970-01-01
      • 2021-02-08
      • 2012-08-07
      • 1970-01-01
      • 1970-01-01
      • 2015-11-20
      • 2011-01-28
      相关资源
      最近更新 更多