我的Spring Web应用程序方法中的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);
不触发