Java spring-MockMvc模型属性测试

Java spring-MockMvc模型属性测试,java,spring,spring-mvc,junit,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.

我有一个控制器方法,我必须为它编写一个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());
}
使用SpringMockMVC进行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设置该值

响应以字符串链形式给出(我猜是json格式,因为它是常见的rest服务响应),因此您可以通过生成的响应以以下方式访问响应字符串:

ResultActions result = mockMvc.perform(get("/new"));
MvcResult mvcResult = result.andExpect(status().isOk()).andReturn();
String jsonResponse = mvcResult.getResponse().getContentAsString();
然后可以通过getResponse()访问响应。getContentAsString()。如果是json/xml,请再次将其作为对象解析并检查结果。下面的代码只是确保json包含字符串链“employeeForm”(使用-我推荐使用)


希望它有帮助…

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

您的模型通常是如何填充的?正如@M.Deinum所说,如果模型没有填充,您就没有填充。您必须模拟会话并将此对象放入其中,此链接可能会帮助您:嗨,Deinum,模型中填充了currentClient,带有aop:aspect,而mockmvcycy不会调用它。您需要确保调用aspect。您能否演示如何初始化测试以及在哪里声明方面?确保方面配置包含在测试配置中就足够了
@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"));
}