简体   繁体   English

spring MockMvc 测试模型属性

[英]spring MockMvc testing for model attribute

I have a controller method for which i have to write a junit test我有一个控制器方法,我必须为它编写一个 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());
}

Junit test using spring mockMVC使用 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"));
}

I am getting NullPointerException as model.asMap().get("currentClient");我收到 NullPointerException 作为 model.asMap().get("currentClient"); is returning null when the test is run, how do i set that value using spring mockmvc framework运行测试时返回 null,我如何使用 spring mockmvc 框架设置该值

The response is given as string chain (I guess json format, as it is the usual rest service response), and thus you can access the response string via the resulting response in this way:响应以字符串链形式给出(我猜是 json 格式,因为它是通常的休息服务响应),因此您可以通过这种方式通过结果响应访问响应字符串:

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

And then you can access to the response via getResponse().getContentAsString().然后您可以通过 getResponse().getContentAsString() 访问响应。 If json/xml, parse it as an object again and check the results.如果是json/xml,再次解析为对象,查看结果。 The following code simply ensures the json contains string chain "employeeForm" (using asertJ - which I recommend)以下代码只是确保 json 包含字符串链“employeeForm”(使用asertJ - 我推荐)

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

Hope it helps...希望它有帮助...

As an easy work around you should use MockHttpServletRequestBuilder.flashAttr() in your test:作为一个简单的解决方法,您应该在测试中使用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"));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM