多语言展示
当前在线:616今日阅读:19今日分享:20

如何创建Springmvc单元测试请求功能模拟web请求

创建Springmvc单元测试请求功能模拟web请求
工具/原料
1

springmvc

2

intellij idea

方法/步骤
1

创建一个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 {           } }

2

传入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 {    } }

3

创建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 { } }

4

模拟发送请求,拿到返回值。@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(); } }

5

请求成功之后,请求域中会有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 pageInfos = (PageInfo)mockHttpServletRequest.getAttribute('pageInfo'); } }

6

打印程序结果:

推荐信息