首页 文章

用String []作为请求体的Mockmvc单元测试

提问于
浏览
1

我尝试使用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:预期状态:<200>但是:<400>

什么是从mockmvc传递字符串数组参数的最佳方法?

1 回答

  • 2

    你把你的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")));
    

    jsonPathorg.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath

相关问题