java – 如何使用MockMVC传递控制器的@RequestBody参数

前端之家收集整理的这篇文章主要介绍了java – 如何使用MockMVC传递控制器的@RequestBody参数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
带有@RequestParam注释的参数可以使用:post(“/ ****** / ***”).param(“variable”,“value”)传递

但是如何传递具有@RequestBody注释的参数值?

我的测试方法是:

  1. @Test
  2. public void testCreateCloudCredential() throws Exception {
  3.  
  4. CloudCredentialsBean cloudCredentialsBean = new CloudCredentialsBean();
  5. cloudCredentialsBean.setCloudType("cloudstack");
  6. cloudCredentialsBean.setEndPoint("cloudstackendPoint");
  7. cloudCredentialsBean.setUserName("cloudstackuserName");
  8. cloudCredentialsBean.setPassword("cloudstackpassword");
  9. cloudCredentialsBean.setProviderCredential("cloudstackproviderCredential");
  10. cloudCredentialsBean.setProviderIdentity("cloudstackproviderIdentity");
  11. cloudCredentialsBean.setProviderName("cloudstackproviderName");
  12. cloudCredentialsBean.setTenantId(78);
  13. cloudCredentialsBean.setCredentialId(98);
  14.  
  15. StatusBean statusBean = new StatusBean();
  16. statusBean.setCode(200);
  17. statusBean.setStatus(Constants.SUCCESS);
  18. statusBean.setMessage("Credential Created Successfully");
  19.  
  20. Gson gson = new Gson();
  21. String json = gson.toJson(cloudCredentialsBean);
  22. ArgumentCaptor<String> getArgumentCaptor =
  23. ArgumentCaptor.forClass(String.class);
  24. ArgumentCaptor<Integer> getInteger = ArgumentCaptor.forClass(Integer.class);
  25.  
  26. ArgumentCaptor<CloudCredentialsBean> getArgumentCaptorCredential =
  27. ArgumentCaptor.forClass(CloudCredentialsBean.class);
  28. when(
  29. userManagementHelper.createCloudCredential(getInteger.capture(),getArgumentCaptorCredential.capture())).thenReturn(
  30. new ResponseEntity<StatusBean>(statusBean,new HttpHeaders(),HttpStatus.OK));
  31.  
  32. mockMvc.perform(
  33. post("/usermgmt/createCloudCredential").param("username","aricloud_admin").contentType(
  34. MediaType.APPLICATION_JSON).content(json)).andExpect(
  35. status().isOk());
  36.  
  37. }

正在测试的控制器方法是:

  1. @RequestMapping(value = "/createCloudCredential",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE,consumes = MediaType.APPLICATION_JSON_VALUE)
  2. @ResponseBody
  3. public ResponseEntity<StatusBean> createCloudCredential(
  4. @RequestParam("userId") int userId,@RequestBody CloudCredentialsBean credential) {
  5. return userManagementHepler.createCloudCredential(userId,credential);
  6. }

我得到的错误是:

如何在此处传递凭证的模拟值?

解决方法

POST请求通常会在其正文中传递其参数.所以我无法通过同一个请求提供参数和内容来理解您的期望.

所以在这里,你可以简单地做:

  1. mockMvc.perform(
  2. post("/usermgmt/createCloudCredential").contentType(
  3. MediaType.APPLICATION_JSON).content(json)).andExpect(
  4. status().isOk());

如果需要传递参数“username = aricloud_admin”,请将其添加到JSON字符串,或者将其作为查询字符串显式传递:

  1. mockMvc.perform(
  2. post("/usermgmt/createCloudCredential?username=aricloud_admin")
  3. .contentType(MediaType.APPLICATION_JSON).content(json))
  4. .andExpect(status().isOk());

猜你在找的Java相关文章