Mockito MVC - 如何为绑定字符串数组的@RequestParam传递值

时间:2016-06-30 01:33:19

标签: java unit-testing spring-mvc mockito

我想用Mockito写一个单元测试。

要测试的方法由 Spring MVC 编写如下:

@RequestMapping(value = "/save", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
@ResponseBody
public String save(String appName,
        @RequestParam(value = "platforms[]") String[] platforms,
        HttpServletRequest request) {}

我尝试了几种方法来模拟请求值平台绑定字符串数组,如' string [] ”。

但是,它似乎仍然无效:平台值为空。

以下是我尝试的方式:

路#1

final String[] platforms = { "Android", "iOS" };
request.setAttribute("platforms", platforms);
request.setAttribute("platforms[]", platforms);

路#2

mockMvc.perform(MockMvcRequestBuilders.post("/application/save")
            .session(session).requestAttr("platforms[]", platforms)
            .requestAttr("platforms", platforms)
            .param("appName", "Just for test"));

注意:request是一个模拟对象( MockHttpServletRequest

希望你能给我一些解决这个问题的想法。感谢。

有关详细信息,请按以下步骤#2执行打印结果:

MockHttpServletRequest:
     HTTP Method = POST
     Request URI = /application/save
      Parameters = {appName=[Just for test]}
         Headers = {}

         Handler:
            Type = com.xxx.controller.ApplicationController
          Method = public java.lang.String com.xxx.controller.ApplicationController.save(java.lang.String,java.lang.String[],javax.servlet.http.HttpServletRequest)

Resolved Exception:
            Type = org.springframework.web.bind.MissingServletRequestParameterException

    ModelAndView:
       View name = null
            View = null
           Model = null

        FlashMap:

 MockHttpServletResponse:
          Status = 400
   Error message = Required String[] parameter 'platforms[]' is not present
         Headers = {}
    Content type = null
            Body = 
   Forwarded URL = null
  Redirected URL = null
         Cookies = []

0 个答案:

没有答案