【问题标题】:How can I make a Hamcrest assert? It should ask that a list of items has a property which is in an other list?如何进行 Hamcrest 断言?它应该问一个项目列表是否具有另一个列表中的属性?
【发布时间】:2021-04-14 00:38:51
【问题描述】:

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

@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' 是

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

你好,詹斯

【问题讨论】:

    标签: java arrays junit hamcrest


    【解决方案1】:

    一种方法是将ListMatchers 传递给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));
    

    【讨论】:

      猜你喜欢
      • 2018-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-05
      • 1970-01-01
      相关资源
      最近更新 更多