我想通过MockMvc
测试这个方法 @RequestMapping("/saveCandidate")
public String saveCandidate(
Model model,
@ModelAttribute("candidateFromRequest") @Validated() Candidate candidateFromRequest,
BindingResult result,
@ModelAttribute("skillsIdList") Set<Skill> skills,
@ModelAttribute("vacanciesForCandidate") Set<Vacancy> vacanciesForCandidate,
@ModelAttribute("eventsForCandidate") Set<Event> eventsForCandidate,
RedirectAttributes redirectAttributes){
...
}
如何将测试方法的BindingResult结果模拟传递给saveCandidate
方法?
我的测试方法:
@Test
public void saveCandidateWithErrors() throws Exception{
BindingResult result= mock(BindingResult.class);
when(result.hasErrors()).thenReturn(true);
when(candidateService.findByName(anyString())).thenReturn(new ArrayList<Candidate>());
MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get("/saveCandidate");
if(result.hasErrors())
//how test code that writing here?
}
else{
//I always hit it here
}
}
我想设置为我的模拟
的结果答案 0 :(得分:2)
你不能(你可以,但这不值得麻烦)。 BindingResult
是Spring在创建命令对象时创建的对象,并在调用saveCandidate
处理程序方法时传递它。
您不应该测试Spring提供的类和对象,您应该在输入正确或错误的请求参数时测试它们的解析方式。
解释为什么它不值得:
Spring使用一堆HandlerMethodArgumentResolver
,RequestMappingHandlerMapping
和HandlerMethod
个实例来处理到达DispatcherServlet
的请求。模拟BindingResult
很可能意味着必须模拟或子类化所有这些。