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

Mag*_*ssi 15 junit spring-mvc jsonpath mockmvc

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

 {  
   "links":[  
      {  
         "rel":[  
            "self"
         ],
         "href":"/"
      },
      {  
         "rel":[  
            "next"
         ],
         "href":"/1"
      }
   ]
}
Run Code Online (Sandbox Code Playgroud)

我试过这个,我可以看到它有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")));
  }
Run Code Online (Sandbox Code Playgroud)

小智 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("/"));
Run Code Online (Sandbox Code Playgroud)

  • 您是否知道是否有一种方法可以在不对数组索引进行硬编码的情况下执行此操作(如果顺序不同)? (3认同)

小智 10

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

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


Men*_*han 5

接受的答案看起来好起来的我。但是我对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("/"))
Run Code Online (Sandbox Code Playgroud)

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

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;
Run Code Online (Sandbox Code Playgroud)

希望这对某人有帮助。尤其是对单元测试不熟悉的人:)