springmvc
intellij idea
创建一个springmvc单元测试类MvcTest:加载spring配置文件和springmvc配置文件@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations={'classpath:applicationContext.xml', 'file:src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml'})public class MvcTest { @Test public void testPage() throws Exception { } }
传入springmvc的ioc@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations={'classpath:applicationContext.xml', 'file:src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml'})@WebAppConfigurationpublic class MvcTest { MockMvc mockMvc; @Autowired WebApplicationContext context; @Test public void testPage() throws Exception { } }
创建MockMvc对象,虚拟mvc请求,获取处理结果。@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations={'classpath:applicationContext.xml', 'file:src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml'})@WebAppConfigurationpublic class MvcTest { MockMvc mockMvc; @Autowired WebApplicationContext context; @Before public void initMockMvc() { mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); } @Test public void testPage() throws Exception { } }
模拟发送请求,拿到返回值。@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations={'classpath:applicationContext.xml', 'file:src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml'})@WebAppConfigurationpublic class MvcTest { MockMvc mockMvc; @Autowired WebApplicationContext context; @Before public void initMockMvc() { mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); } @Test public void testPage() throws Exception { MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get('/emps').param('pn', '1')).andReturn(); } }
请求成功之后,请求域中会有pageInfo.@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations={'classpath:applicationContext.xml', 'file:src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml'})@WebAppConfigurationpublic class MvcTest { MockMvc mockMvc; @Autowired WebApplicationContext context; @Before public void initMockMvc() { mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); } @Test public void testPage() throws Exception { MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get('/emps').param('pn', '1')).andReturn(); MockHttpServletRequest mockHttpServletRequest = mvcResult.getRequest(); PageInfo
打印程序结果: