我正在运行以下测试,以检查两个列表是否相同:
public void testSortInputStream() throws IOException {
field = "User ID";
streamSorter.sort(inputStream, outputStream, comparator);
Reader actualCSVReader = new BufferedReader(outputStreamToInputStreamReader(outputStream));
Reader expectedCSVReader = new BufferedReader(new InputStreamReader(expectedStream));
List<CSVRecord> actualCSVRecords = CSVFormat.RFC4180.parse(actualCSVReader).getRecords();
List<CSVRecord> expectedCSVRecords = CSVFormat.RFC4180.parse(expectedCSVReader).getRecords();
Assert.assertEquals(expectedCSVRecords, actualCSVRecords);
}
奇怪的是,断言失败并显示以下消息:
expected: java.util.ArrayList<[CSVRecord [comment=null, mapping=null, recordNumber=1, values=[10, Ruby, Wax, ruby, Employee, 12-12-2014 08:09:13]], CSVRecord [comment=null, mapping=null, recordNumber=2, values=[3, David, Payne, Dpayne, Manager, 23-09-2014 09:35:02]]]>
but was: java.util.ArrayList<[CSVRecord [comment=null, mapping=null, recordNumber=1, values=[10, Ruby, Wax, ruby, Employee, 12-12-2014 08:09:13]], CSVRecord [comment=null, mapping=null, recordNumber=2, values=[3, David, Payne, Dpayne, Manager, 23-09-2014 09:35:02]]]>
但是,如果将两个列表进行比较,它们是绝对相同的。我在这里想念什么?
最佳答案
根据链接的CSVRecord
's javadoc,CSVRecord
不会覆盖equals(Object)
-它继承了java.lang.Object
的默认实现。因此,您不能依赖它进行相等性检查,包括嵌套检查(例如List<CSVRecord>
)。这并不完美,但是您可以使用的一个肮脏技巧是将CSVRecord
转换为字符串,并比较它们的表示形式:
List<String> actualCSVRecords =
CSVFormat.RFC4180
.parse(actualCSVReader)
.getRecords()
.stream()
.map(Object::toString)
.collect(Collectors.toList());
List<String> expectedCSVRecords =
CSVFormat.RFC4180
.parse(expectedCSVReader)
.getRecords()
.stream()
.map(Object::toString)
.collect(Collectors.toList());
Assert.assertEquals(expectedCSVRecords, actualCSVRecords);