Java 在Spring boot web app方法的这个测试用例中,如何省略NullPointerException?
我的SpringWebApp方法中的重定向属性确实存在问题。方法如下:Java 在Spring boot web app方法的这个测试用例中,如何省略NullPointerException?,java,spring,unit-testing,junit,Java,Spring,Unit Testing,Junit,我的SpringWebApp方法中的重定向属性确实存在问题。方法如下: @RequestMapping("/employee") public String saveEmployee(@ModelAttribute EmployeeCommand commandObject){ EmployeeCommand savedCommand = employeeService.saveEmployeeCommand(commandObject); return "redirect:
@RequestMapping("/employee")
public String saveEmployee(@ModelAttribute EmployeeCommand commandObject){
EmployeeCommand savedCommand = employeeService.saveEmployeeCommand(commandObject);
return "redirect:/employee/" + savedCommand.getId();
}
我写了一个测试:
@Test
public void saveEmployee() throws Exception {
//given
EmployeeCommand employeeCommand = new EmployeeCommand();
employeeCommand.setId(2L);
//when
when(employeeService.saveEmployeeCommand(employeeCommand)).thenReturn(employeeCommand);
//then
mockMvc.perform(post("/employee"))
.andExpect(status().isOk());
.andExpect(redirectedUrl("redirect:/employee/2"));
verify(employeeService, times(1)).saveEmployeeCommand(employeeCommand);
}
我不断得到一个与该行相关的NullPointerException
:
return "redirect:/employee/" + savedCommand.getId();
似乎savedCommand
为空。有什么建议吗?尝试使用
mockMvc.perform(post("/employee")).flashAttr("commandObject", employeeCommand));
现在,您只执行post请求,而不传递commandObject,因此此模拟:
when(employeeService.saveEmployeeCommand(employeeCommand)).thenReturn(employeeCommand);
不触发您没有收到任何错误吗?存钱的时候有什么吗?没有。我要买吗?我试试看。如果我将
employeeCommand
更改为any()
,这是否也有效?它也适用于any()
,但当传递null
时,这也会触发-通常最好使用any(employeeCommand.class)
至少确保参数类型正确