gpt4 book ai didi

java - 模型属性的 spring MockMvc 测试

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:02:31 24 4
gpt4 key购买 nike

我有一个 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/

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