hamcrest:使用hamcrest在逻辑上比较两个集合ob自定义类

时间:2018-10-25 14:03:18

标签: java hamcrest

我有两个Collection<Dumb>,需要使用hamcrest进行比较:

public class Dumb {
    private String id;

    //setters & getters
}

简短直接

@Test
public void test() {
    Collection<Dumb> actual = new ArrayList<Dumb>();
    Dumb actualDumbOne = new Dumb();
    actualDumbOne.setId("1");
    Dumb actualDumbTwo = new Dumb();
    actualDumbTwo.setId("2");
    actual.add(actualDumbOne);
    actual.add(actualDumbTwo);

    Collection<Dumb> expected = new ArrayList<Dumb>();
    Dumb expectedDumbOne = new Dumb();
    expectedDumbOne.setId("1");
    Dumb expectedDumbTwo = new Dumb();
    expectedDumbTwo.setId("2");
    expected.add(expectedDumbOne);
    expected.add(expectedDumbTwo);

    assertThat(expected, containsInAnyOrder(actual));
}

由于以下原因而失败

Expected: iterable over [<[Dumb@56114349, Dumb@46c28400]>] in any order
     but: Not matched: <Dumb@2d6abfc7>

重要:我无法更改Dumb代码,它是第三方类。 重要:我需要比较Dumb.id is equals to Dumb.id

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如果只需要比较Dumb.id成员,则可以将ID提取到列表中并比较生成的ID列表。

    List<String> actualIds = actual.stream().map(Dumb::getId).collect(Collectors.toList());
    List<String> expectedIds = expected.stream().map(Dumb::getId).collect(Collectors.toList());

    assertThat(expectedIds, containsInAnyOrder(actualIds.toArray()));