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

时间:2014-09-02 01:18:36

标签: spring-mvc junit jsonpath mockmvc

我很难弄清楚如何在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")));
  }

3 个答案:

答案 0 :(得分:14)

如何添加多个和Expect 方法?类似于:

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

答案 1 :(得分:1)

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

const x: {
    a: string;
    b: number[];
}

我将在此处添加静态导入(对于初学者而言),因为当我刚开始工作时,我必须确定几个导入中的哪个导入。

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("/"))

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

答案 2 :(得分:0)

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

ftp.storbinary(f'STOR {os.path.split(myfile)[1]}', open(myfile, 'rb'))