11

I have a controller method for which i have to write a junit test

@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

@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"); is returning null when the test is run, how do i set that value using spring mockmvc framework

nagendra
  • 593
  • 1
  • 9
  • 29
  • How is your model normally being filled? – M. Deinum Oct 01 '13 at 12:14
  • just like @M.Deinum said, You havn't filled the model, if it is not filled. – Jaiwo99 Oct 01 '13 at 12:39
  • You have to mock your session and put this object in it, this link may help you: http://stackoverflow.com/questions/13687055/spring-mvc-3-1-integration-tests-with-session-support – Jaiwo99 Oct 01 '13 at 12:42
  • Hi Deinum, Model is filled with currentClient with an aop:aspect, which is not being called with mockMVC – nagendra Oct 01 '13 at 14:12
  • You need to make sure the aspect gets called. Can you show how you initialize the test and where is the aspect declared? It should be enough to make sure the aspect configuration is included in the test configuration – Ulises Nov 25 '15 at 04:05

2 Answers2

2

As an easy work around you should use MockHttpServletRequestBuilder.flashAttr() in your test:

@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"));
}
Arne Burmeister
  • 20,046
  • 8
  • 53
  • 94
0

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:

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(). If json/xml, parse it as an object again and check the results. The following code simply ensures the json contains string chain "employeeForm" (using asertJ - which I recommend)

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

Hope it helps...

Alexcocia
  • 128
  • 9