gpt4 book ai didi

java - 如何在Spring boot Web应用程序方法的这个测试用例中省略NullPointerException?

转载 作者:行者123 更新时间:2023-12-02 11:29:27 24 4
gpt4 key购买 nike

我的 Spring Web 应用程序方法中的重定向属性确实存在问题。方法如下:

@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);

不触发

关于java - 如何在Spring boot Web应用程序方法的这个测试用例中省略NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49384450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com