我尝试使用String []作为请求主体
为下面的PUT api创建单元测试@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:期望的状态:&lt; 200&gt;但是:&lt; 400&gt;
从mockmvc传递字符串数组参数的最佳方法是什么?
答案 0 :(得分:3)
你把你的String []放在param中。你sohuld把它放在体内。你可以这样说(我假设你正在使用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())
.andExpect(jsonPath("$.[0]", is("1")));
jsonPath
是org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath