2014-09-02 57 views
9

我很難弄清楚如何在spring mvc的JSON文檔響應中聲明jsonPath。也許有一個比使用jsonPath來完成這個更好的方法。我想驗證鏈接數組中有一個rel屬性爲「self」,並且「self」對象的「href」屬性也具有等於「/」的「href」屬性。 JSON響應看起來是這樣的:用JSONPath和spring mvc斷言數組的數組

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

回答

9

如何增加幾個andExpect的方法呢?類似於:

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

您是否知道是否有辦法在不對數組索引進行硬編碼的情況下執行此操作(如果順序不同)? – 2017-04-25 16:10:24

+0

凱文,你可以在你的jsonpath中使用regexp,就像這個$ .links [?(@。rel =〜/.*self/i)]或類似的東西。請在這裏查看完整的文檔:https://github.com/json-path/JsonPath – 2017-04-28 15:22:20