使用JUnit时的AssertionError

时间:2014-03-29 02:16:55

标签: java junit

我收到的异常中的消息错误是

  

预期:sg.team7ft.model.TransactionReportItem@2c2dc991但是:sg.team7ft.model.TransactionReportItem@720c653f

我认为数据类型是相同的,我不知道它为什么抛出异常。

我的源代码是:

    ArrayList<TransactionReportItem> tranItemReport = new ArrayList<TransactionReportItem>();   
    tranItemReport.add(new TransactionReportItem("NUS Notepad", "Great Notepad for those lectures", "Annand B", 1, "21/04/2014"));
    tranItemReport.add(new TransactionReportItem("Centenary Jumper", "A really nice momento", "Danial B", 1, "21/04/2014"));

    ArrayList<TransactionReportItem> tranItemReportTests = report.generateTransactionReport(startDate, endDate);

    Iterator<TransactionReportItem> tranReportI = tranItemReportTests.iterator();
    int i = 0;
    while(tranReportI.hasNext())
    {
        TransactionReportItem tranReportTe = tranReportI.next();
    //  assertEquals(tranReportTe.getQuantity(), tranItemReport.get(i).getQuantity());
        try
        {
            assertEquals(tranReportTe, tranItemReport.get(i));
        }
        catch(AssertionError e)
        {
            String msg = e.getMessage();
        }
        i++;
    }

1 个答案:

答案 0 :(得分:2)

您必须在自定义类.equals()中实施.hashCode()(并且衡量标准为TransactionReportItem)。

assertEquals()将使用.equals()方法断言您提供的两个对象是相同的。但是,标准实现并不是您想要的:通常您希望根据对象所持有的值来确定相等性。

要全面了解如何实现这一点,请仔细阅读以下主题:

What issues should be considered when overriding equals and hashCode in Java?