我怎样才能让 Hamcrest 断言?它应该问一个项目列表有一个在另一个列表中的属性吗?

问题描述

好的,我有一个数据库,里面装满了 Mandantentity 的随机对象类型。我有一个查找器,它通过给定的 id 数组查找项目。 我想检查返回的列表是否包含我要求的所有项目(ids)(ids 数组),所以我想这样做:

@Test
public void testFindById() {
    long[] ids = new long[10];
    for (int j = 0; j < ids.length; j++) {
        long l = ids[j];
        Mandantentity mandantentity = getMandant(j);
        Mandantentity save = mandantRepository.save(mandantentity);
        ids[j] = save.getId();
    }


    final List<Mandantentity> entities = mandantRepository.findById(ids);

    assertTrue(entities.size() == ids.length);
    assertthat(entities,contains(hasProperty("id",contains(ids))));

}

但不起作用...

java.lang.AssertionError: 预期:可迭代包含 [hasProperty("id",可迭代包含 [[,]])] 但是:项目 0:属性 'id' 是

我不知道如何安排。 有人有想法吗?

问候詹斯

解决方法

一种方法是将 ListMatcher 传递给 contains

List<Matcher<Object>> expected = Arrays.stream(ids)
    .mapToObj(id -> hasProperty("id",equalTo(id)))
    .collect(Collectors.toList());

assertThat(entities,contains(expected));

如果你打算经常这样做,你可以把它放在一个辅助方法中:

private static <E> Matcher<Iterable<? extends E>> containsWithProperty(String propertyName,List<?> propertyValues) {
    List<Matcher<? super E>> itemMatchers = propertyValues.stream()
        .map(value -> hasProperty(propertyName,equalTo(value)))
        .collect(Collectors.toList());

    return contains(itemMatchers);
}

用法:

// Convert ids array to a List
List<Long> idList = Arrays.stream(ids)
    .boxed()
    .collect(Collectors.toList());

assertThat(entities,containsWithProperty("id",idList));