java - 使用 JUnit 时出现断言错误

标签 java junit

我收到的异常消息错误是

expected:sg.team7ft.model.TransactionReportItem@2c2dc991 but was: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++;
    }

最佳答案

您必须在自定义类TransactionReportItem中实现.equals()(以及更好的措施:.hashCode())。

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

有关如何实现这一点的全面概述,请阅读本主题:

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

关于java - 使用 JUnit 时出现断言错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22726182/

相关文章:

java - 不幸的是我的 map 已经停止工作。安卓

java - 如何让 Facebook 登录带我去 Activity ?

java - FTP - 如果将 WAR 文件显示为网站,则客户端会下载 WAR 文件

java - 是否有用 Java 实现的验证 HTML 解析器?

java - 我如何为 android fragment 类编写单元测试?

java - split 方法中使用多个正则表达式

java - 为什么 ExpectedException 在 Spring 中被弃用

java - 将 assertArrayEquals() 与通配符一起使用?

java - 处理 Pokerhand 游戏中重复牌的异常时出错..

java - 是否有多进程单元测试框架/junit 插件?