在比较两个相同的列表时,assertEquals失败

时间:2017-01-04 12:11:20

标签: java list collections junit

我正在运行以下测试以检查两个列表是否相同:

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]]]>

但是,如果比较两个列表,它们完全相同。我在这里错过了什么?

1 个答案:

答案 0 :(得分:1)

根据您关联的CSVRecord's javadocCSVRecord不会覆盖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);
相关问题