2016-03-05 13 views
1

春季方法,我想測試如何使用MockMVC檢查Spring Unittest中的returntype?

@RequestMapping(value="/files", method=RequestMethod.GET) 
@ResponseBody 
public List<FileListRequest> get() { 
    return getMainController().getAllFiles(); 
} 

我要放心/文件用列表[FileListRequest]回覆所有來電。怎麼樣?
這是測試應該是的方法。

@Test 
public void testGetAll() throws Exception { 
    this.mockMvc.perform(get("/files").accept("application/json")) 
      .andExpect(status().isOk()) 
      .andExpect(content().contentType(SOMETHING); 
} 

我可以簡單地更換SOMETHING還是完全錯誤?

我可以對perform()返回的對象運行assert方法嗎?

+0

你可以使用'JSON path'測試是否響應包含的具體數據 – Pragnani

回答

1

編輯:

MvcResult result = this.mockMvc.perform(get("/files").accept("application/json")) 
      .andExpect(status().isOk()) 
      .andReturn(); 

String content = result.getResponse().getContentAsString(); 

//使用GSON或傑克遜

ObjectMapper mapper = new ObjectMapper(); 
TypeFactory typeFactory=objectMapper.getTypeFactory(); 
List<SomeClass> someClassList =mapper.readValue(content , typeFactory.constructCollectionType(List.class, SomeClass.class)); 

//與您的清單斷言這裏轉換JSON字符串到相應的對象


你可以使用Json Path來檢查是否有特定的數據IST在您迴應

從舊的項目代碼剪斷

mockMvc.perform(get("/rest/blogs")) .contentType(MediaType.APPLICATION_JSON)) 
       .andExpect(jsonPath("$.blogs[*].title", 
         hasItems(endsWith("Title A"), endsWith("Title B")))) 
       .andExpect(status().isOk()); 
+0

有我的方式,我可以直接與預期收益的工作對象,在這種情況下,列表? – Dai

+0

@John是的,我會用編輯更新答案,但不建議像這樣測試休息響應。 – Pragnani

+0

好的。我只需要檢查一件事:返回類型是期望的返回類型(是否有返回的列表,...)。返回對象的確切內容在這一刻並不重要。 – Dai

相關問題