帶有@RequestParam註釋的參數可以通過使用:post(「/ ******/***」)。param(「variable」,「value」 )如何通過使用MockMVC傳遞控制器的@RequestBody參數
但我怎麼傳遞具有@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);
}
對不起,我沒有得到你在暗示什麼 – dexter
對不起,如果我不明白這個問題,但如果你問如何在模擬中傳遞'@ RequestBody',你可以在你的例子中找到你的解決方案:'mockkMvc。執行( 後(「/ usermgmt/creat eCloudCredential「).param(」username「,」aricloud_admin「)。contentType( MediaType.APPLICATION_JSON).content(json))''。你之前已經將它轉換爲json:'String json = gson.toJson(cloudCredentialsBean);'並且用content(json)'傳遞了內容。這是你想要的嗎? – Pau
@PauChorro但這不起作用 – dexter