如何使用MockMvc传递ModelAttrubute参数?(How to pass ModelAt

2019-10-18 18:39发布

我有这样的HTML表单春天:

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

我很困惑。

Answer 1:

当浏览器需要提交一个表单,其典型地串行化形式<input>字段如网址编码的参数。 因此,当您需要模拟的HttpServletRequest ,你需要将这些相同的参数添加到请求。

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

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



Answer 2:

可以通过在所需的@ModelAttribute与对象.flashAttr()像这样的方法:

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


文章来源: How to pass ModelAttrubute parameters using MockMvc?