2017-04-12 64 views
1

在我的春節,控制器我有一個返回以下JSON的方法:單元測試Spring MVC的REST服務:陣列jsonPath

[ 
    { 
    "id": 2, 
    "dto": null, 
    "user": { 
     "userId": 2, 
     "firstName": "Some", 
     "lastName": "Name", 
     "age": 100, 
     "aboutMe": "boring" 
    }, 
    "isYoung": false, 
    "isOk": false 
    } 
] 

我想寫這個getter.Here測試是我的測試:

@Test 
public void getterMethod() throws Exception{ 
    mockMvc.perform(get("/path?id=1")).andExpect(status().isOk()) 
     .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) 
     .andExpect(jsonPath("$[0].id", is(2))) 
     .andExpect(jsonPath("$[2].user.userId", is(2))) 
     .andExpect(jsonPath("$[2].user.firstName", is("Giorgos"))) 
     .andExpect(jsonPath("$[2].user.lastName", is("Ant"))) 
     .andExpect(jsonPath("$[3].isYoung", is(false))) 
     .andExpect(jsonPath("$[4].isOk", is(false))); 
} 

顯然我沒有得到這個權利:

雖然如果我只爲$運行測試[0] .ID測試通過。然而,對於所有其他情況(對於嵌套的用戶對象和isYoung fiels和isOk),我得到一個數組索引異常錯誤。

有什麼建議嗎?謝謝!

+1

如果所有的數組索引爲0?由於測試JSON中只有一個元素? – James

回答

2

如果測試是:

@Test 
public void getterMethod() throws Exception{ 
    mockMvc.perform(get("/path?id=1")).andExpect(status().isOk()) 
     .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) 
     .andExpect(jsonPath("$[0].id", is(2))) 
     .andExpect(jsonPath("$[0].user.userId", is(2))) 
     .andExpect(jsonPath("$[0].user.firstName", is("Some"))) 
     .andExpect(jsonPath("$[0].user.lastName", is("Name"))) 
     .andExpect(jsonPath("$[0].isYoung", is(false))) 
     .andExpect(jsonPath("$[0].isOk", is(false))); 
}