我有一个 Controller 方法,我必须为其编写一个 junit 测试
@RequestMapping(value = "/new", method = RequestMethod.GET)
public ModelAndView getNewView(Model model) {
EmployeeForm form = new EmployeeForm()
Client client = (Client) model.asMap().get("currentClient");
form.setClientId(client.getId());
model.addAttribute("employeeForm", form);
return new ModelAndView(CREATE_VIEW, model.asMap());
}
使用spring mockMVC进行Junit测试
@Test
public void getNewView() throws Exception {
this.mockMvc.perform(get("/new")).andExpect(status().isOk()).andExpect(model().attributeExists("employeeForm")
.andExpect(view().name("/new"));
}
我得到 NullPointerException 作为 model.asMap().get("currentClient");运行测试时返回 null,我如何使用 spring mockmvc 框架设置该值
最佳答案
作为一种简单的解决方法,您应该在测试中使用 MockHttpServletRequestBuilder.flashAttr()
:
@Test
public void getNewView() throws Exception {
Client client = new Client(); // or use a mock
this.mockMvc.perform(get("/new").flashAttr("currentClient", client))
.andExpect(status().isOk())
.andExpect(model().attributeExists("employeeForm"))
.andExpect(view().name("/new"));
}
关于java - 模型属性的 spring MockMvc 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19115681/