SpringMVC Mock測試實現(xiàn)原理及實現(xiàn)過程詳解
什么是mock測試?
在測試過程中,對于某些不容易構(gòu)成或者不容易獲取的對象,用一個虛擬的對象來創(chuàng)建以便測試的測試方法,就是Mock測試。
Servlet、Request、Response等Servlet API相關(guān)對象本來就是由Servlet容器(Tomcat)創(chuàng)建的。
這個虛擬的對象就是Mock對象。
Mock對象是真實對象在調(diào)試期間的代替品。
為什么使用Mock測試?
- 避免開發(fā)模塊之間的耦合
- 輕量、簡單、靈活
MockMVC介紹
MockMvcBuilder
他是用來構(gòu)造MockMVC的構(gòu)造器
主要有兩個實現(xiàn):StandaloneMockMvcBuilder和DefaultMockMvcBuilder,分別對應(yīng)之前的兩種測試方式。
我們直接使用靜態(tài)工廠MockMvcBuilders創(chuàng)建即可。
MockMvcBuilders
負(fù)責(zé)創(chuàng)建MockMvcBuilder對象
有兩種創(chuàng)建方式
1、standaloneSetup(Object... controllers)
2、webAppContextSetup(WebApplicationContext wac):指定WebApplicationContext,將會從該上下文獲取相應(yīng)的控制器并得到相應(yīng)的MockMvc
MockMvc
對于服務(wù)器端的Spring MVC測試支持主入口點。
通過MockMvcBuilder構(gòu)造
MockMvcBuilder由MockMvcBuilders的靜態(tài)方法去構(gòu)造。
核心方法:perform(RequestBuilder requestBuilder)---->執(zhí)行一個RequestBuilder請求,會自動執(zhí)行SpringMvc的流程并映射到相應(yīng)的控制器執(zhí)行處理,該方法的返回值是一個ResultActions;
ResultActions
andExpect
添加ResultMatcher驗證規(guī)則,驗證控制器執(zhí)行完成后結(jié)果是否正確。
andDo
添加ResultHandler結(jié)果處理器,比如調(diào)試時打印結(jié)果到控制臺;
andReturn
最后返回相應(yīng)的MvcResult;然后進(jìn)行自定義驗證/進(jìn)行下一步的異步處理。
MockMvcRequestBuilders
- 用來構(gòu)造請求
- 主要由兩個子類MockHttpServletRequestBuilder和MockMultipartHttpServletRequestBuilder(如文件上傳),即用來Mock客戶端請求需要的所有數(shù)據(jù)。
MockMvcResultMatchers
- 用來匹配執(zhí)行完請求后的結(jié)果驗證
- 如果匹配失敗將拋出相應(yīng)的異常
- 包含了很多驗證API方法
MockMvcResultHandlers
- 結(jié)果處理器,表示要對結(jié)果做點什么事情
- 比如此處使用MockMvcResultHandlers.print()輸出整個相應(yīng)結(jié)果信息。
MvcResult
單元測試執(zhí)行結(jié)果,可以針對執(zhí)行結(jié)果進(jìn)行自定義驗證邏輯。
MocMvc的使用
添加依賴
<!-- spring 單元測試組件包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
<!-- 單元測試Junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
測試類
TestMockMVC.java
package com.cyb.ssm.controller.test;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
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.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
//@WebAppConfiguration:可以在單元測試的時候,不用啟動Servlet容器,就可以獲取一個Web應(yīng)用上下文
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/*.xml")
@WebAppConfiguration
public class TestMockMVC {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void Setup() {
// 初始化一個MockMVC對象的方式有兩種:單獨設(shè)置、web應(yīng)用上下文設(shè)置
// 建議使用web應(yīng)用上下文設(shè)置
mockMvc = new MockMvcBuilders().webAppContextSetup(wac).build();
}
@Test
public void test() throws Exception {
// 通過perform去執(zhí)行一個Http請求
// andExpect:通過該方法,判斷請求執(zhí)行是否成功
// andDo:對請求之后的結(jié)果,進(jìn)行輸出
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/item/showEdit").param("id", "1"))
.andExpect(MockMvcResultMatchers.view().name("item/item-edit"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
System.out.println("===============");
System.out.println(result.getHandler());
}
}
運行結(jié)果如下
JRE Oracle Corporation/13.0.1 is not supported, advanced source lookup disabled.
12月 12, 2019 4:48:43 下午 org.springframework.test.context.support.AbstractTestContextBootstrapper getDefaultTestExecutionListenerClassNames
信息: Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
12月 12, 2019 4:48:43 下午 org.springframework.test.context.support.AbstractTestContextBootstrapper getTestExecutionListeners
信息: Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@4470f8a6, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@7c83dc97, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@7748410a, org.springframework.test.context.support.DirtiesContextTestExecutionListener@740773a3, org.springframework.test.context.transaction.TransactionalTestExecutionListener@37f1104d, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@55740540]
12月 12, 2019 4:48:43 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from file [D:\JAVA\eclipse_setup\ssm-project\target\classes\spring\applicationContext-dao.xml]
12月 12, 2019 4:48:43 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from file [D:\JAVA\eclipse_setup\ssm-project\target\classes\spring\applicationContext-service.xml]
12月 12, 2019 4:48:43 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from file [D:\JAVA\eclipse_setup\ssm-project\target\classes\spring\applicationContext-tx.xml]
12月 12, 2019 4:48:43 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from file [D:\JAVA\eclipse_setup\ssm-project\target\classes\spring\springmvc.xml]
12月 12, 2019 4:48:43 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.web.context.support.GenericWebApplicationContext@50ad3bc1: startup date [Thu Dec 12 16:48:43 CST 2019]; root of context hierarchy
12月 12, 2019 4:48:44 下午 org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
信息: Mapped "{[/item/updateItem],produces=[application/json;charset=utf8]}" onto public com.cyb.ssm.po.Item com.cyb.ssm.controller.ItemController.updateItem(java.lang.Integer,java.lang.String,java.lang.Float,com.cyb.ssm.po.Item,org.springframework.web.multipart.MultipartFile) throws java.lang.Exception
12月 12, 2019 4:48:44 下午 org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
信息: Mapped "{[/item/testRedirect],produces=[application/json;charset=utf8]}" onto public java.lang.String com.cyb.ssm.controller.ItemController.testRedirect(javax.servlet.http.HttpServletRequest)
12月 12, 2019 4:48:44 下午 org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
信息: Mapped "{[/item/testForward],produces=[application/json;charset=utf8]}" onto public java.lang.String com.cyb.ssm.controller.ItemController.testForward(javax.servlet.http.HttpServletRequest)
12月 12, 2019 4:48:44 下午 org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
信息: Mapped "{[/item/findItem],produces=[application/json;charset=utf8]}" onto public java.lang.String com.cyb.ssm.controller.ItemController.findItem(java.lang.Integer)
12月 12, 2019 4:48:44 下午 org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
信息: Mapped "{[/item/queryItem],produces=[application/json;charset=utf8]}" onto public org.springframework.web.servlet.ModelAndView com.cyb.ssm.controller.ItemController.queryItem() throws com.cyb.ssm.exception.CustomException
12月 12, 2019 4:48:44 下午 org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
信息: Mapped "{[/item/queryItem2],produces=[application/json;charset=utf8]}" onto public com.cyb.ssm.po.Item com.cyb.ssm.controller.ItemController.queryItem2(com.cyb.ssm.po.ItemQueryVO)
12月 12, 2019 4:48:44 下午 org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
信息: Mapped "{[/item/deleteItem],produces=[application/json;charset=utf8]}" onto public void com.cyb.ssm.controller.ItemController.deleteItem(java.lang.String[])
12月 12, 2019 4:48:44 下午 org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
信息: Mapped "{[/item/saveItem],produces=[application/json;charset=utf8]}" onto public java.util.Date com.cyb.ssm.controller.ItemController.saveItem(java.util.Date)
12月 12, 2019 4:48:44 下午 org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
信息: Mapped "{[/item/showEdit],produces=[application/json;charset=utf8]}" onto public org.springframework.web.servlet.ModelAndView com.cyb.ssm.controller.ItemController.showEdit(java.lang.Integer)
12月 12, 2019 4:48:44 下午 org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
信息: Mapped "{[/item/batchUpdateItem],produces=[application/json;charset=utf8]}" onto public java.util.List<com.cyb.ssm.po.Item> com.cyb.ssm.controller.ItemController.batchUpdateItem(com.cyb.ssm.po.ItemQueryVO)
12月 12, 2019 4:48:44 下午 org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
信息: Mapped "{[/queryItemByIdWithRest]}" onto public com.cyb.ssm.po.Item com.cyb.ssm.controller.RestItemController.queryItemById()
12月 12, 2019 4:48:44 下午 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
信息: Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@50ad3bc1: startup date [Thu Dec 12 16:48:43 CST 2019]; root of context hierarchy
12月 12, 2019 4:48:44 下午 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
信息: Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@50ad3bc1: startup date [Thu Dec 12 16:48:43 CST 2019]; root of context hierarchy
12月 12, 2019 4:48:44 下午 org.springframework.mock.web.MockServletContext log
信息: Initializing Spring FrameworkServlet ''
12月 12, 2019 4:48:44 下午 org.springframework.web.servlet.FrameworkServlet initServletBean
信息: FrameworkServlet '': initialization started
12月 12, 2019 4:48:44 下午 org.springframework.web.servlet.FrameworkServlet initServletBean
信息: FrameworkServlet '': initialization completed in 17 ms
com.cyb.ssm.po.Item@1ad9b8d3
MockHttpServletRequest:
HTTP Method = GET
Request URI = /item/showEdit
Parameters = {id=[1]}
Headers = {}
Body = <no character encoding set>
Session Attrs = {}
Handler:
Type = com.cyb.ssm.controller.ItemController
Method = public org.springframework.web.servlet.ModelAndView com.cyb.ssm.controller.ItemController.showEdit(java.lang.Integer)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = item/item-edit
View = null
Attribute = item
value = com.cyb.ssm.po.Item@1ad9b8d3
errors = []
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Language=[en]}
Content type = null
Body =
Forwarded URL = /WEB-INF/jsp/item/item-edit.jsp
Redirected URL = null
Cookies = []
===============
public org.springframework.web.servlet.ModelAndView com.cyb.ssm.controller.ItemController.showEdit(java.lang.Integer)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于Java中throw和throws的區(qū)別(詳解)
下面小編就為大家?guī)硪黄贘ava中throw和throws的區(qū)別(詳解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-07-07
Java 數(shù)據(jù)結(jié)構(gòu)與算法系列精講之字符串暴力匹配
字符串暴力匹配算法是指在一個長字符串中暴力尋找是否包含某一子串所謂暴力匹配,就是不使用任何其他算法,將兩個字符串中的字符一一進(jìn)行比對2022-02-02
SpringBoot之使用Feign實現(xiàn)微服務(wù)間的交互
這篇文章主要介紹了SpringBoot中使用Feign實現(xiàn)微服務(wù)間的交互,對微服務(wù)這方面感興趣的小伙伴可以參考閱讀本文2023-03-03
Java中使用RediSearch實現(xiàn)高效的數(shù)據(jù)檢索功能
RediSearch是一款構(gòu)建在Redis上的搜索引擎,它為Redis數(shù)據(jù)庫提供了全文搜索、排序、過濾和聚合等高級查詢功能,本文將介紹如何在Java應(yīng)用中集成并使用RediSearch,以實現(xiàn)高效的數(shù)據(jù)檢索功能,感興趣的朋友跟著小編一起來看看吧2024-05-05
java隨機(jī)生成字符串(字符隨機(jī)生成類 生成隨機(jī)字符組合)
java隨機(jī)生成字符串,字符組合多樣,可以大小字組合、大+小字符+數(shù)字等方式,大家參考使用吧2013-12-12

