如何使用模拟控制器MockMvc

时间:2013-10-16 14:54:03

标签: java testing spring-mvc mocking spring-test-mvc

我有这种控制器方法:

@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 个答案:

答案 0 :(得分:0)

使用MockMvc,您不能。 MockMvc是一种HTTP客户端。您使用MockMvcRequestBuilders生成HTTP请求,设置标头,请求参数,正文和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