【问题标题】:Asserting array of arrays with JSONPath and spring mvc使用 JSONPath 和 spring mvc 断言数组数组
【发布时间】:2014-09-02 01:18:36
【问题描述】:

我很难弄清楚如何在 spring mvc 的 JSON 文档响应中使用 jsonPath 进行断言。也许有比在这个特定场景中使用 jsonPath 更好的方法来实现这一点。我想验证链接数组有一个“self”的rel项,并且“self”对象的“href”属性也有一个等于“/”的“href”属性。 JSON 响应如下所示:

 {  
   "links":[  
      {  
         "rel":[  
            "self"
         ],
         "href":"/"
      },
      {  
         "rel":[  
            "next"
         ],
         "href":"/1"
      }
   ]
}

我试过这个,我可以看到它有 rel [0] 有 self 但我宁愿不依赖于链接数组和 rel 数组中 self 的位置,并实际测试链接 [rel] 的 href 是什么[自我] 是“/”。 有什么想法吗?

 @Before
  public void setup() {
    MockitoAnnotations.initMocks(this);
    mockMvc = MockMvcBuilders.standaloneSetup(welcomeController).build();
  }

  @Test
  public void givenRootUrl_thenReturnLinkToSelf() throws Exception {
    mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
        .andExpect(jsonPath("$.links[0].rel[0].", is("self")));
  }

【问题讨论】:

    标签: spring-mvc junit jsonpath mockmvc


    【解决方案1】:

    添加几个 andExpect 方法怎么样?类似于:

    mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
        .andExpect(jsonPath("$.links[0].rel[0]", is("self")))
        .andExpect(jsonPath("$.links[0].href[0]", is("/"));
    

    【讨论】:

    • 你知道是否有一种方法可以在不硬编码数组索引的情况下做到这一点(以防顺序不同)?
    • Kevin,您可以在 jsonpath 中使用正则表达式,例如 $.links[?(@.rel =~ /.*self/i)] 或类似的东西。请在此处查看完整文档:github.com/json-path/JsonPath
    • 此方法不适用于 HashSet,因为元素的顺序不确定
    【解决方案2】:

    如果你不想硬编码数组索引值,我想你可以这样做

    MockMvc.perform(get("/"))
    .andDo(print()).andExpect(status().isOk())
    .andExpect(jsonPath("$.links[*].rel").value(Matchers.containsInAnyOrder(Matchers.containsInAnyOrder(Matchers.is("self")))));
    

    【讨论】:

      【解决方案3】:

      Accepted answer 在我看来还不错。但是我对junit4不熟悉。因此,我将在此处添加如何使用 Junit5 测试典型场景。

      mockMvc.perform(get("/"))
          .andDo(print())
          .andExpect(status().isOk())
          .andExpect(jsonPath("$.links", hasSize(2)))
          .andExpect(jsonPath("$.links[0].rel[0]")
              .value("self"))
          .andExpect(jsonPath("$.links[0].href[0]")
              .value("/"))
      

      我将在这里添加静态导入(如果是初学者),因为当我第一次工作时,我必须确定几个导入中的哪些导入。

      import org.springframework.test.web.servlet.MockMvc;
      import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
      import static org.hamcrest.Matchers.hasSize;
      import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
      import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
      

      希望这对某人有所帮助。特别是单元测试新手:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-13
        • 1970-01-01
        • 2020-02-16
        • 1970-01-01
        • 2016-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多