hamcrest:在逻辑上使用 hamcrest 比较两个集合 ob custom class
hamcrest: comparing two collections ob custom class logically using 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
代码,它是第三方 class。
重要:我需要比较那个Dumb.id is equals to Dumb.id
。
有什么想法吗?
如果你只需要比较Dumb.id个成员,你可以将ids提取到一个列表中,然后比较得到的id-list。
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()));
我有两个 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
代码,它是第三方 class。
重要:我需要比较那个Dumb.id is equals to Dumb.id
。
有什么想法吗?
如果你只需要比较Dumb.id个成员,你可以将ids提取到一个列表中,然后比较得到的id-list。
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()));