Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring MockMvc testing for model attribute

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

like image 351
nagendra Avatar asked Oct 01 '13 12:10

nagendra


1 Answers

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"));
}
like image 199
Arne Burmeister Avatar answered Nov 15 '22 13:11

Arne Burmeister