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;然后進行自定義驗證/進行下一步的異步處理。
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é)果進行自定義驗證邏輯。
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é)果,進行輸出 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)文章
關(guān)于Https協(xié)議和HttpClient的實現(xiàn)詳解
這篇文章主要給大家介紹了關(guān)于Https協(xié)議和HttpClient實現(xiàn)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-05-05Java中Spring MVC接收表單數(shù)據(jù)的常用方法
Spring MVC是Spring框架中的一個模塊,用于開發(fā)基于MVC(Model-View-Controller)架構(gòu)的Web應(yīng)用程序,它提供了一種輕量級的、靈活的方式來構(gòu)建Web應(yīng)用,同時提供了豐富的功能和特性,本文給大家介紹了Spring MVC接收表單數(shù)據(jù)的方法,需要的朋友可以參考下2024-05-05Java項目在Idea中開發(fā)遇到所有代碼爆紅的問題與解決辦法
今天打開項目時發(fā)現(xiàn)idea竟然爆紅,通過查找相關(guān)資料用于解決,下面這篇文章主要給大家介紹了關(guān)于Java項目在Idea中開發(fā)遇到所有代碼爆紅的問題與解決辦法的相關(guān)資料,需要的朋友可以參考下2023-06-06詳解Java實現(xiàn)數(shù)據(jù)結(jié)構(gòu)之并查集
并查集這種數(shù)據(jù)結(jié)構(gòu),可能出現(xiàn)的頻率不是那么高,但是還會經(jīng)常性的見到,其理解學(xué)習(xí)起來非常容易,通過本文,一定能夠輕輕松松搞定并查集2021-06-06