2017-09-19 41 views
0

我試圖與下面的PUT API創建單元測試的String []作爲請求主體與Mockmvc單元測試的String []作爲請求主體

@RequestMapping(value = "/test/id", method = RequestMethod.PUT) 
public ResponseEntity<?> updateStatus(@RequestBody String[] IdList,.........) 
{ 
} 

和我的測試去如下

@Test 
    public void updateStatus() throws Exception { 
     when(serviceFactory.getService()).thenReturn(service);   

     mockMvc.perform(put(baseUrl + "/test/id) 
         .param("IdList",new String[]{"1"})) 
         .andExpect(status().isOk()); 

    } 

測試與下面的異常 java.lang.AssertionError失敗:狀態預計:< 200>卻被:< 400>

什麼合作是從mockmvc傳遞字符串數組參數的最好方法嗎?

回答

0

你把你的String []放在參數中。你把它放在身體裏。你可以這樣說(我假設你使用的是json,如果你使用xml,你可以相應地改變它):

ObjectMapper mapper = new ObjectMapper(); 
String requestJson = mapper.writeValueAsString(new String[]{"1"}); 
mockMvc.perform(put(baseUrl + "/test/id) 
        .contentType(MediaType.APPLICATION_JSON_UTF8).content(requestJson) 
        .andExpect(status().isOk()); 
+0

真棒...工作,因爲它..謝謝.. – kns