我正在尝试使用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: Status expected:<200> but was:<400>
从mockmvc传递字符串数组参数的最佳方法是什么?
您正在将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())
.andExpect(jsonPath("$.[0]", is("1")));
jsonPath
是 org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句