Reputation: 43
I'm trying to create a unit test for the PUT api, as seen below, with a String[] as the request body.
@RequestMapping(value = "/test/id", method = RequestMethod.PUT)
public ResponseEntity<?> updateStatus(@RequestBody String[] IdList,.........){
}
and my test is shown below
@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());
}
The test is failing with this exception:
java.lang.AssertionError: Status expected:<200> but was:<400>
What could be the best way to pass a string array param from mockmvc?
Upvotes: 3
Views: 3887
Reputation: 3154
You are putting your String[] in param. You sohuld put it in body. You can put it like that(I am assuming you are using json. If you use xml you can change it accordingly):
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
is org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath
Upvotes: 4