通常而言,咱們寫好一個模塊後,會對其進行單元測試,再集成到現有的系統中。java
可是呢~針對Controller、Service、Dao三層來講,咱們最常的是對Service和Dao進行單元測試。然而Controller的測試,不少人仍是啓動Tomcat,使用Postman進行api測試,這樣不只須要等待很長的編譯部署時間,並且沒法逐個Controller功能進行單獨測試,所以特地總結Controller層的單元測試。順便說下,Postman挺好用的,只是咱們仍然須要啓動tomcat,有點浪費時間。spring
那麼,咱們須要有一種不需啓動tomcat就能夠測試controller層的方法。數據庫
接下來咱們細細講來。api
controller所採用的是SpringMVC框架 。SpringMVC已經繼承了單元測試的類tomcat
@RunWith(SpringJUnit4ClassRunner.class) // 此處調用Spring單元測試類 @WebAppConfiguration // 調用javaWEB的組件,好比自動注入ServletContext Bean等等 @ContextConfiguration(locations = { "classpath:context.xml", "classpath:mvccontext.xml" }) // 加載Spring配置文件 public class TestPayTypeController { @Autowired PayTypeController payTypeController;//測試的controller類 @Autowired ServletContext context; MockMvc mockMvc; @Before public void setup() { mockMvc = MockMvcBuilders.standaloneSetup(payTypeController).build(); } }
注意:服務器
@WebAppConfiguration若是不加的話,是無法調用WEB的一些特性的。常常會被遺忘掉。。。mvc
@ContextConfiguration中,須要把全部Spring的配置文件所有加載進來,由於有的項目中Spring 的xml配置是分拆的。 此處的xml是放在resources的根目錄中。app
MockMvc是SpringMVC提供的Controller測試類框架
每次進行單元測試時,都是預先執行@Before中的setup方法,初始化PayTypeController單元測試環境。工具
ResultAction是用來模擬Browser發送FORM表單請求的。get()是請求的地址,accept()請求的內容 ;
@org.junit.Test // get請求 public void getListTest() throws Exception { // 發送請求 ResultActions resultActions = this.mockMvc .perform(MockMvcRequestBuilders.get("/paytype/list/all").accept(MediaType.APPLICATION_JSON)); MvcResult mvcResult = resultActions.andReturn(); String result = mvcResult.getResponse().getContentAsString(); System.out.println("客戶端獲的數據:" + result); }
在控制檯打印以下,說明成功了!
ResultAction是用來模擬Browser發送FORM表單請求的。post()是請求的地址,accept()請求的內容 param()請求的鍵值對,若是有多個參數能夠後綴調用多個param();
MvcResult是得到服務器的Response內容。
@org.junit.Test // post請求 public void addTest() throws Exception { // 發送請求 ResultActions resultActions = this.mockMvc.perform(MockMvcRequestBuilders.post("/paytype/add") .accept(MediaType.APPLICATION_JSON).param("typename", "一年停").param("payfee","4444.0").param("payto", "post")); MvcResult mvcResult = resultActions.andReturn(); String result = mvcResult.getResponse().getContentAsString(); System.out.println("客戶端獲的數據:" + result); }
成功插入數據庫;
通常經常使用的就get,post請求;至此,咱們不需啓動tomcat就能測試controller層的method。
@RequestMapping(value = "/add", method = RequestMethod.POST) public ResultMessage add(PayTypeModel ptm) throws Exception { ResultMessage result = new ResultMessage(); payTypeService.add(ptm); result.setResult("Y"); result.setMessage("增長繳費類型成功"); return result; } @RequestMapping(value="/get",method=RequestMethod.GET) public PayTypeModel get(@RequestParam int typeno) throws Exception { return payTypeService.get(typeno); }
若有錯誤,歡迎留言指正!