gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:00:18 24 4
gpt4 key购买 nike

我收到的异常消息错误是

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com