1. 程式人生 > >SSM_CRUD新手練習(7)Spring單元測試分頁請求

SSM_CRUD新手練習(7)Spring單元測試分頁請求

          好久沒寫這個系列部落格了是因為本人去公司實習去了,公司用的是Spring+SpingMvc+Hibernate現在有時間了不管怎麼樣繼續把這個專案寫完。

  因為機器的原因,我的環境變成了IDEA+oracle+1.8+tomcat8.5,不過不影響,只是資料庫的配置不同和匯入的是oracle的jar包罷了。

  那就繼續吧,我們已經寫了一個分頁的後臺控制器,和前面一樣我們使用Spring單元測試有沒有問題,能不能取出資料。

  在測試之前我們要知道,我們需要給後臺的分頁控制器傳送一個請求,它才能處理這個請求給我們返回資料。Spring單元測試方便就在於它能模擬請求。

  在test目錄下新建MvcTest檔案:

package com.atguigu.crud.test;

import com.atguigu.crud.bean.Employee;
import com.github.pagehelper.PageInfo;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
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.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import java.util.List; /** * 使用Spring測試模組提供的測試請求功能,測試curd請求的正確性 * Spring4測試的時候,需要servlet3.0的支援 * */ @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(locations= {"classpath:applicationContext.xml","file:E:/project/ssm_crud/src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml"}) public class MvcTest { // 傳入Springmvc的ioc @Autowired WebApplicationContext context; // 虛擬mvc請求,獲取到處理結果。 MockMvc mockMvc; @Before public void initMokcMvc(){ mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); } @Test public void testPage() throws Exception { //模擬請求拿到返回值 MvcResult result=mockMvc.perform(MockMvcRequestBuilders.get("/emps").param("pn","5")).andReturn(); //請求成功以後,請求域中會有pageInfo;我們可以取出pageInfo進行驗證 MockHttpServletRequest request=result.getRequest(); PageInfo pi = (PageInfo) request.getAttribute("pageInfo"); System.out.println("當前頁碼:"+pi.getPageNum()); System.out.println("總頁碼:"+pi.getPages()); System.out.println("總記錄數:"+pi.getTotal()); System.out.println("在頁面需要連續顯示的頁碼"); int[] nums = pi.getNavigatepageNums(); for (int i : nums) { System.out.print(" "+i); } System.out.println(); //獲取員工資料 List<Employee> list = pi.getList(); for (Employee employee : list) { System.out.println("ID:" + employee.getEmpId() + "==>Name:" + employee.getEmpName()); } } }

  測試結果為:

  

 可以看到沒有問題0.0