【问题标题】:How to use MockMvc with mock of controller如何将 MockMvc 与控制器模拟一起使用
【发布时间】:2013-10-24 18:18:25
【问题描述】:

我有这个控制器方法:

@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 ) 的两个变量

我怎样才能做到?

【问题讨论】:

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


    【解决方案1】:

    使用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
    

    【讨论】:

    • 如果我使用 MockMvc,result.andExpect(MockMvcResultMatchers.view().name(/*我可以在这里期待什么?*/))
    • @gstackoverflow 你可以这样做,但你不会嘲笑BindingResult。您必须发送会使Event 参数无效的请求参数。
    • 如何通过 http 请求使 Event 无效?
    • 在调试中我看到它是空的
    • @gstackoverflow 这是一个很长的解释,我不想添加到这个答案中,因为它与您的问题没有直接关系。 Please read this chapter of the documentation。然后去阅读整个文档,因为您的理解似乎存在漏洞。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 2014-08-15
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    相关资源
    最近更新 更多