How to pass ModelAttrubute parameters using MockMvc?

不问归期 提交于 2019-12-24 15:09:39

问题


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

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

I very confused.


回答1:


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

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




回答2:


You can pass in the required @ModelAttribute object with the .flashAttr() method like so:

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


来源:https://stackoverflow.com/questions/19430365/how-to-pass-modelattrubute-parameters-using-mockmvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!