How to test a spring controller method by using MockMvc? How to test a spring controller method by using MockMvc? spring spring

How to test a spring controller method by using MockMvc?


You can use your applications dispatcher servlet xml using the following annoations. The following example is hitting a controller with the path /mysessiontest setting some session attributes and expecting a certain view to be returned:

import org.junit.Before;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.MediaType;import org.springframework.mock.web.MockHttpServletRequest;import org.springframework.mock.web.MockHttpSession;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import org.springframework.test.context.web.WebAppConfiguration;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.web.servlet.setup.MockMvcBuilders;import org.springframework.web.context.WebApplicationContext;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;@RunWith(SpringJUnit4ClassRunner.class)@WebAppConfiguration@ContextConfiguration({ "classpath:springDispatcher-servlet.xml" })public class MySessionControllerTest {    @Autowired WebApplicationContext wac;     @Autowired MockHttpSession session;    @Autowired MockHttpServletRequest request;    private MockMvc mockMvc;    @Before    public void setup() {        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();    }    @Test    public void getAccount() throws Exception {        UserDomain user = new UserDomain();        user.setFirstName("johnny");        session.setAttribute("sessionParm",user);        this.mockMvc.perform(get("/mysessiontest").session(session)        .accept(MediaType.TEXT_HTML))        .andExpect(status().isOk())        .andExpect(view().name("test"));    }}