Pregunta

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.

¿Fue útil?

Solución

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.

Otros consejos

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

request.flashAttr("myVacancy", new Vacancy()));
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top