Как использовать MockMvc с макетом контроллера
У меня есть этот метод контроллера:
@RequestMapping(value = "/addEvent", method = RequestMethod.POST)
public String addEvent(Model model,
@Valid @ModelAttribute("myEvent") Event event,
BindingResult result, RedirectAttributes redirectAttributes,
@RequestParam(required = true) Integer selectedEventTypeId,
@RequestParam(required = true) Integer selectedEventStatusId) {
if (result.getErrorCount() > 1 ){
return "eventDetailsAdd";
}
eventService.addEvent(event, selectedEventTypeId, selectedEventStatusId);
redirectAttributes.addAttribute("idEvent", event.getId());
redirectAttributes.addAttribute("message", "added correctly at " + new Date() );
return "redirect:eventDetails";
}
Используя mockMvc, я хочу смоделировать результат и проверить оба варианта if (result.getErrorCount() > 1 )
Как я могу это сделать?
1 ответ
Решение
С MockMvc
, ты не можешь. MockMvc
это тип HTTP-клиента. Вы генерируете свой HTTP-запрос с помощью MockMvcRequestBuilders
, установите заголовки, параметры запроса, тело и URL. MockMvc
будет издеваться над отправкой запроса с интеграцией полного DispatcherServlet
стек.
Если вы хотите издеваться над BindingResult
аргумент, я предлагаю вам проверить свои @Controller
класс самостоятельно.
// in @Test
MyController controller = new MyController(/* maybe other arguments */)
// generate your mocks and declare expectations
controller.addEvent(/* mocks go here */);
// verify your mocks