java - 模型属性的 spring MockMvc 测试

标签 java spring spring-mvc junit

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

相关文章:

java - 将字符串java中的数字相加

java - 为什么 Elastic Beanstalk 停止工作?

java - Spring Boot @RestControllerAdvice 没有捕获自定义异常

java - 如何让表达式语言跨多个jsp页面跳转?

java - Thymeleaf:URL 中的参数未被替换

hibernate - Spring amqp 消费者 - 第一次尝试时出现 "No Session found for current thread"错误

java - java swing中多个多边形上的鼠标事件

java - 如何在同一个文件中设置项目名称/组/版本,以及 {source,target} 兼容性?

java - Spring框架中回调方法和Bean后处理器的区别

java - Spring Security 和 DB 授权