spring MockMvc测试模型属性

时间:2013-10-01 12:03:59

标签: java spring spring-mvc junit

我有一个控制器方法,我必须编写一个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 framework

设置该值

2 个答案:

答案 0 :(得分:0)

响应以字符串链的形式给出(我猜json格式,因为它是通常的休息服务响应),因此您可以通过这样的方式通过结果响应访问响应字符串:

ResultActions result = mockMvc.perform(get("/new"));
MvcResult mvcResult = result.andExpect(status().isOk()).andReturn();
String jsonResponse = mvcResult.getResponse().getContentAsString();

然后您可以通过getResponse()。getContentAsString()访问响应。如果是json / xml,再次将其解析为对象并检查结果。以下代码只是确保json包含字符串链“employeeForm”(使用asertJ - 我推荐)

assertThat(mvcResult.getResponse().getContentAsString()).contains("employeeForm")

希望它有所帮助...

答案 1 :(得分:0)

作为一个简单的解决方法,您应该在测试中使用 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"));
}