Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在Spring boot web app方法的这个测试用例中,如何省略NullPointerException?_Java_Spring_Unit Testing_Junit - Fatal编程技术网

Java 在Spring boot web app方法的这个测试用例中,如何省略NullPointerException?

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:

我的SpringWebApp方法中的重定向属性确实存在问题。方法如下:

@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)
至少确保参数类型正确