2

我写了这个控制器方法:

  @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;
    }

我可以用什么方法测试这个方法是否得到 Candidate ?

我使用 MockMvc。

4

1 回答 1

0

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

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

于 2013-10-03T13:53:29.770 回答