如何使用Hamcrest在Junit中的列表中声明相同的响应

问题描述

我想断言每个对象是否都包含相同的值,例如: 以下代码我在列表中有20个响应对象,我期望 每个响应的“状态”为“确定”,“消息”为“成功” 测试时在列表中。 但是下面的代码仅检查列表中的第一个响应对象。我如何迭代其余部分并检查每一个 无需编写冗余代码即可完成响应。

@Test
  public void testName(){
    List<Response> responseList = new ArrayList<Response>();
    Response response1 = new Response("OK","Success");  // only able to iterate this object
    Response response2= new Response("OK","Success");
    Response response3= new Response("OK","Success");
    .................................................
    Response response20 = new Response("Ok","Success");

    responseList.addAll(Arrays.asList(response1,response2,response3,....,response20));

    assertthat(responseList,Matchers.hasItems(allOf(Matchers.<Item>hasProperty("status",is("OK")),Matchers.<Item>hasProperty("message",is("Success")))));

解决方法

最后,我找到了解决方案:我必须检查everyItem()并为我工作

assertThat(items,Matchers.everyItem(allOf(Matchers.hasProperty(“ firstName”,is(“ test”))), Matchers.hasProperty(“ lastName”,is(“ best”))))));