带有@RequestParam注释的参数可以通过以下方式传递:post(“/ ****** / ***”)。param(“variable”,“value”)
但是如何传递具有@RequestBody注释的参数值?
我的测试方法是:
@Test
public void testCreateCloudCredential() throws Exception {
CloudCredentialsBean cloudCredentialsBean = new CloudCredentialsBean();
cloudCredentialsBean.setCloudType("cloudstack");
cloudCredentialsBean.setEndPoint("cloudstackendPoint");
cloudCredentialsBean.setUserName("cloudstackuserName");
cloudCredentialsBean.setPassword("cloudstackpassword");
cloudCredentialsBean.setProviderCredential("cloudstackproviderCredential");
cloudCredentialsBean.setProviderIdentity("cloudstackproviderIdentity");
cloudCredentialsBean.setProviderName("cloudstackproviderName");
cloudCredentialsBean.setTenantId(78);
cloudCredentialsBean.setCredentialId(98);
StatusBean statusBean = new StatusBean();
statusBean.setCode(200);
statusBean.setStatus(Constants.SUCCESS);
statusBean.setMessage("Credential Created Successfully");
Gson gson = new Gson();
String json = gson.toJson(cloudCredentialsBean);
ArgumentCaptor<String> getArgumentCaptor =
ArgumentCaptor.forClass(String.class);
ArgumentCaptor<Integer> getInteger = ArgumentCaptor.forClass(Integer.class);
ArgumentCaptor<CloudCredentialsBean> getArgumentCaptorCredential =
ArgumentCaptor.forClass(CloudCredentialsBean.class);
when(
userManagementHelper.createCloudCredential(getInteger.capture(),
getArgumentCaptorCredential.capture())).thenReturn(
new ResponseEntity<StatusBean>(statusBean, new HttpHeaders(),
HttpStatus.OK));
mockMvc.perform(
post("/usermgmt/createCloudCredential").param("username", "aricloud_admin").contentType(
MediaType.APPLICATION_JSON).content(json)).andExpect(
status().isOk());
}
正在测试的控制器方法是:
@RequestMapping(value = "/createCloudCredential", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<StatusBean> createCloudCredential(
@RequestParam("userId") int userId,
@RequestBody CloudCredentialsBean credential) {
return userManagementHepler.createCloudCredential(userId, credential);
}
答案 0 :(得分:9)
POST
请求通常会在其正文中传递param
。因此,同一个请求同时提供param
和content
,我无法理解您的期望。
所以在这里,你可以做到:
mockMvc.perform(
post("/usermgmt/createCloudCredential").contentType(
MediaType.APPLICATION_JSON).content(json)).andExpect(
status().isOk());
如果您需要传递参数"username=aricloud_admin"
,请将其添加到JSON
字符串,或者将其作为查询字符串显式传递:
mockMvc.perform(
post("/usermgmt/createCloudCredential?username=aricloud_admin")
.contentType(MediaType.APPLICATION_JSON).content(json))
.andExpect(status().isOk());