2012-09-06 42 views
0

這是我的控制器方法:Spring測試-MVC PUT不支持

@RequestMapping(method = RequestMethod.PUT,produces="application/json", headers = "content-type=application/json") 
    public @ResponseBody User updateUser(@RequestBody User user) throws PropertyErrorException, ItemNotFoundException {   
     return service.UpdateUser(user);  
    } 

使用Spring測試MVC我想編寫一個單元測試用例:

@Test 
public void UpdateUser() throws Exception {  
    mockMvc.perform(put("/r01/users").body(userJsonString.getBytes()) 
     .accept(MediaType.APPLICATION_JSON)) 
     .andExpect(status().isOk()) 
     .andExpect(content().type(MediaType.APPLICATION_JSON)) 
     .andExpect(content().string(userString)); 
} 

運行這個測試case生成:

WARN org.springframework.web.servlet.PageNotFound - Request method 'PUT' not supported 

此外,updateUser方法從未被調用和響應代碼是405.

我寫了很多測試,所有的GET請求,他們正常工作。這意味着我對ContextConfiguration有信心。我錯過了什麼?

+0

一年後。這裏有同樣的問題。你有沒有要求提出要求?在此先感謝,橡樹 – oak

+0

好吧,我得到它我轉換爲JSON也沒有二傳手getters。那裏的請求被拒絕了。我的解決方案是跳過那些獲得者。即:ObjectMapper mapper = new ObjectMapper(); mapper.configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS,true); return mapper.writeValueAsBytes(object);' – oak

回答

3

您明確期待在您的@RequestMapping方法中的content-type的頭部,但不會在請求中發送內容類型,我認爲這就是請求失敗的原因。

mockMvc.perform(put("/r01/users").contentType(MediaType.APPLICATION_JSON).body(userJsonString.getBytes()) 
    .accept(MediaType.APPLICATION_JSON)) 
    .andExpect(status().isOk()) 
    .andExpect(content().type(MediaType.APPLICATION_JSON)) 
    .andExpect(content().string(userString)); 
+0

我試過了「contentType(MediaType.APPLICATION_JSON)」沒有區別。 –

+0

只是嘗試一些不同的東西,如果你刪除'headers =「content-type = application/json」'它仍然不起作用嗎? –

+0

嗨。我已經試過了,並且圍繞這個主題做了很多排列組合。 –