[英]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.