[英]how to test ModelAttribute parameter by MockMvc
我写了这个控制器方法:
@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。
您不能专门测试该方法将接收Candidate
参数。 您的选择是发送错误的请求数据,从而使Spring无法正确实例化它并返回400错误(但这可能由于其他原因而发生)。 或发送正确的数据并收到您通常期望的结果。
请注意,您不应该测试Spring功能。 使用第3方框架时,您假设它已经过正确的测试,尤其是像Spring这样的框架。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.