【问题标题】:How to Assert same response from list in Junit using hamcrest如何使用 hamcrest 从 Junit 中的列表中断言相同的响应
【发布时间】:2020-11-09 19:48:41
【问题描述】:

我想断言每个对象是否包含相同的值,例如:在 以下代码我在列表中有 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")))));

【问题讨论】:

    标签: java junit hamcrest


    【解决方案1】:

    最后我找到了解决方案:我必须检查everyItem(),它对我有用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多