如何使用MockMvc传递ModelAttrubute参数? [英] How to pass ModelAttrubute parameters using MockMvc?

查看:510
本文介绍了如何使用MockMvc传递ModelAttrubute参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个html弹簧形式:

I have this html spring form:

<form:form action="addVacancy" modelAttribute="myVacancy">
        <form:label path="name">name</form:label>
        <form:input path="name" ></form:input>
        <form:errors path="name" cssClass="error" />
        <br>
        <form:label path="description">description</form:label>
        <form:input path="description" id="nameInput"></form:input>
        <form:errors path="description" cssClass="error" />
        <br>
        <form:label path="date">date</form:label>
        <input type="date" name="date" />
        <form:errors path="date" cssClass="error" />
        <br>
        <input type="submit" value="add" />
    </form:form>

我通过这种方法处理此表格:

I handle this form by this method:

@RequestMapping("/addVacancy")
    public ModelAndView addVacancy(@ModelAttribute("myVacancy") @Valid Vacancy vacancy,BindingResult result, Model model,RedirectAttributes redirectAttributes){
        if(result.hasErrors()){
            model.addAttribute("message","validation error");
            return new ModelAndView("vacancyDetailsAdd");
        }
        vacancyService.add(vacancy);
        ModelAndView mv = new ModelAndView("redirect:goToVacancyDetails");
        mv.addObject("idVacancy", vacancy.getId());
        redirectAttributes.addAttribute("message", "added correctly at "+ new Date());
        return mv;
    }

如何提出相同的请求,该请求是在提交表单后获得的.这必须通过MockMvc来完成.

How to make the same request, which is obtained after submitting the form. This must be done by means of MockMvc.

@Test
public void testMethod(){
    MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get("/addVacancy");
    //what must I  write here?
    ResultActions result = mockMvc.perform(request);
}

我很困惑.

推荐答案

当浏览器需要提交表单时,通常会将表单<input>字段序列化为url编码的参数.因此,当您要模拟HttpServletRequest时,需要将那些相同的参数添加到请求中.

When a browser needs to submit a form, it typically serializes the form <input> fields as url-encoded parameters. Therefore, when you want to mock an HttpServletRequest, you need to add those same parameters to the request.

request.param("name", "some value")
       .param("description", "description value")
       .param("date", "some acceptable representation of date");

DispatcherServlet将使用这些参数来创建一个Vacancy实例,并将其作为参数传递给您的处理程序方法.

The DispatcherServlet will use these parameters to create a Vacancy instance to pass as an argument to your handler method.

这篇关于如何使用MockMvc传递ModelAttrubute参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆