问题 使用JSONPath和spring mvc断言数组数组


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

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

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

 @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")));
  }

6587
2017-09-02 01:18


起源



答案:


如何添加几个 andExpect 方法?类似于:

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

11
2018-04-14 10:27



你知道如果没有硬编码数组索引(如果顺序不同)有没有办法做到这一点? - Kevin M
凯文,你可以在你的jsonpath中使用regexp,比如$ .links [?(@。rel =〜/。* self / i)]或类似的东西。请查看完整文档: github.com/json-path/JsonPath - Akmal Rakhimov


答案:


如何添加几个 andExpect 方法?类似于:

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

11
2018-04-14 10:27



你知道如果没有硬编码数组索引(如果顺序不同)有没有办法做到这一点? - Kevin M
凯文,你可以在你的jsonpath中使用regexp,比如$ .links [?(@。rel =〜/。* self / i)]或类似的东西。请查看完整文档: github.com/json-path/JsonPath - Akmal Rakhimov