【问题标题】:how to test ModelAttribute parameter by MockMvc如何通过 MockMvc 测试 ModelAttribute 参数
【发布时间】:2013-10-03 13:23:50
【问题描述】:

我写了这个控制器方法:

  @RequestMapping("/submitFormAdd")
        public ModelAndView submitFormAdd(
                Model model,
                @ModelAttribute("myCandidate") @Valid Candidate myCandidate,
                BindingResult result,
                RedirectAttributes redirectAttributes) {
            if (result.hasErrors()) {
                return new ModelAndView("candidateDetailsAdd");
            }

            myCandidate.setDate(new Date());
            candidateService.add(myCandidate);

            redirectAttributes.addAttribute("message", "added Correctly at "+ new Date() );
            redirectAttributes.addAttribute("id", myCandidate.getId());
            ModelAndView modelAndView = new ModelAndView(
                    "redirect:loadCandidateById");
            return modelAndView;
        }

更新

myCandidate 实例所以:

@ModelAttribute(value = "myCandidate")
    public Candidate loadCandidateById(
            @RequestParam(required = false) Integer candidateId) {
        if (candidateId != null)
            return candidateService.findById(candidateId);
        return null;
    }

我可以用什么方法测试这个方法是否获得候选?

我使用 MockMvc。

【问题讨论】:

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


    【解决方案1】:

    您无法具体测试该方法是否会接收Candidate 参数。您的选择是发送错误的请求数据,从而使 Spring 无法正确实例化它并返回 400 错误(但这可能由于其他原因而发生)。或者发送正确的数据并接收您通常期望的数据。

    请注意,您不应该测试 Spring 功能。当您使用第 3 方框架时,您假设它已经过正确测试,尤其是像 Spring 这样的框架。

    【讨论】:

    • @user2740224 如果这就是你得到它的方式,那么我会测试那个特定的方法。 Spring 将正确地将其解析为您的处理程序方法的参数。相信它。
    • 我可以测试 loadCandidateById 方法会在 submitFormAdd 方法之前调用吗?
    • @user2740224 不,您可以单独测试它们。
    • 可能存在测试这些方法调用顺序的方法?
    • @user2740224 不是通过MockMvc。这些测试可能存在于 Spring 单元测试中。您不需要对其进行单元测试,它超出了您的代码范围。集成测试会告诉你它是有效的。
    猜你喜欢
    • 2015-07-29
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多