如何使用MockMvc传递ModelAttrubute参数?

时间:2013-10-17 15:03:59

标签: java spring spring-mvc mocking spring-test

我有这个html spring形式:

<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>

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

@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来完成。

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

我很困惑。

2 个答案:

答案 0 :(得分:6)

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

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

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

答案 1 :(得分:1)

您可以使用@ModelAttribute方法传递所需的.flashAttr()对象,如下所示:

request.flashAttr("myVacancy", new Vacancy()));