如何使用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”))))));

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...