[英]How to pass @RequestBody parameter of controller using MockMVC
帶有@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);
}
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());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.