[英]how to test ModelAttribute parameter by MockMvc
I wrote this controller method: 我写了这个控制器方法:
@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;
}
UPDATE 更新
myCandidate instantiants so: myCandidate实例,因此:
@ModelAttribute(value = "myCandidate")
public Candidate loadCandidateById(
@RequestParam(required = false) Integer candidateId) {
if (candidateId != null)
return candidateService.findById(candidateId);
return null;
}
What way can I test that this method gets Candidate ? 我可以通过什么方法测试此方法是否可以候选?
I use MockMvc. 我使用MockMvc。
You cannot test specifically that the method will receive the Candidate
argument. 您不能专门测试该方法将接收
Candidate
参数。 Your options are to either send bad request data and therefore make Spring unable to correctly instantiate it and return a 400 error (but that can happen for other reasons). 您的选择是发送错误的请求数据,从而使Spring无法正确实例化它并返回400错误(但这可能由于其他原因而发生)。 Or send correct data and receive what you normally expect.
或发送正确的数据并收到您通常期望的结果。
Note that you shouldn't be testing Spring functionality. 请注意,您不应该测试Spring功能。 When you use a 3rd party framework, you assume that it has been tested properly, especially one like Spring.
使用第3方框架时,您假设它已经过正确的测试,尤其是像Spring这样的框架。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.