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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38843218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:41:20  来源:igfitidea点击:

How to pass @RequestBody parameter of controller using MockMVC

javaspring-mvcjunitmockito

提问by dexter

Parameters with @RequestParam annotation can be passed by using : post("/******/***").param("variable", "value")

带有@RequestParam 注解的参数可以通过使用:post("/******/***").param("variable", "value")

but how can I pass value of parameter having @RequestBody annotation?

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

My test method is :

我的测试方法是:

@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());

    }

Controller method that is being tested is :

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

@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);
        }   

Error that I am getting is : enter image description hereHow can I pass a mock value for credentialhere?

我得到的错误是: 在此处输入图片说明如何在此处传递凭证的模拟值?

采纳答案by Serge Ballesta

A POSTrequest normally passes its paramin its body. So I cannot understand what you expect by giving both a paramand a contentfor same request.

POST请求通常通过它的param在其主体中。所以我无法理解你对同一个请求同时给出 aparam和 a 的期望content

So here, you can simply do:

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

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

If you need to pass the parameter "username=aricloud_admin", add it to the JSONstring, or alternatively, pass it explicitly as a query string:

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

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