1

我有这个 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);
}

我很困惑。

4

2 回答 2

6

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

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

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

于 2013-10-17T15:37:21.507 回答
1

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

request.flashAttr("myVacancy", new Vacancy()));
于 2017-09-14T09:22:45.753 回答