Detailed MockMvc

★ MockMvc - SpringMVC independent testing unit testing:
I. Introduction
Why use MockMvc?
        When the module integration testing, hoping to test the Controller by entering a URL, if the server is started by the establishment http client testing, this will make testing becomes very troublesome, for example, slow startup, testing and certification inconvenient, dependent on network environment, it can be tested in order to Controller, we introduced MockMVC.
        MockMvc realized simulation Http request can be directly used in the form of a network, switch to invoke the Controller so that the test speed can not rely on the network environment, but also provides a means of verification, so that the request may validate the tax and very convenient.

Second, the test logic

MockMvcBuilder configuration MockMvc constructor;

Perform mockMvc call, performing a RequestBuilder request, invoke the business process logic controller;

perform return ResultActions, returning operation result, ResultActions, provides a unified authentication;

StatusResultMatchers used to verify the results of the request;

Use ContentResultMatchers the content returned by the request for authentication;

Three, MockMvcBuilder
MockMvc is a very useful class in the spring test, they need to be initialized in the setUp.
MockMvcBuilder is used to construct MockMvc constructor which there are two implementations: StandaloneMockMvcBuilder and DefaultMockMvcBuilder, the former inherited latter.
① MockMvcBuilders.webAppContextSetup (WebApplicationContext context): Specifies the WebApplicationContext, will be acquired from the respective controller and to obtain a corresponding context MockMvc;
② MockMvcBuilders.standaloneSetup (Object ... Controllers): specifies a set of parameters through the controller, so that not need to obtain from the context, such this.mockMvc = MockMvcBuilders.standaloneSetup (this.controller) .build ( );
which also provides additional Builder api, can self Baidu

Four, MockMvcRequestBuilders
        can be seen from the name, RequestBuilder used to build a request, which provides a method buildRequest (ServletContext servletContext) for constructing MockHttpServletRequest; There are two major subclasses MockHttpServletRequestBuilder and MockMultipartHttpServletRequestBuilder (such as file uploads use), i.e., for Mock client requests all the required data.
The main API:
MockHttpServletRequestBuilder GET (UrlTemplate String, Object ... the URLVariables): According worth uri uri variables to the template and RequestBuilder way of a GET request, if the controller method is the method of choice RequestMethod.GET, that corresponds to the controllerTest You must use MockMvcRequestBuilders.get.
post (String urlTemplate, Object ... urlVariables ): with get similar, but is the POST method;
PUT (UrlTemplate String, Object ... the URLVariables): Similar to the get, but it is PUT method;
the Delete (String UrlTemplate, Object .. . urlVariables): with get similar, but is DELETE methods;
Options (UrlTemplate String, Object ... the URLVariables): similar to the get, but it is OPTIONS method;

Five, ResultActions
    call after MockMvc.perform (RequestBuilder requestBuilder) get ResultActions, for ResultActions following three treatment:

ResultActions.andExpect: Add after the completion of the implementation of the assertion. Add ResultMatcher validation rules, to verify the results after the completion of the controller is correct;

ResultActions.andDo: Add a result of processors, such as used herein .andDo (MockMvcResultHandlers.print ()) in response to a result output of the entire information can be used when debugging.

ResultActions.andReturn: return the results indicates execution is completed

Note:
    the ResultHandler a result of a process corresponding to the process, such as the output information for the entire request / response and the like to facilitate debugging, Spring mvc testing framework provides MockMvcResultHandlers static factory method, the plant provides ResultHandler print () returns one output MvcResult details to achieve ResultHandler console

example:


   
   
  1. String example= "{"id ":1, "name ":"kqzu "}";  
  2. mockMvc.perform(post( "/user")   // 路径
  3.             .contentType(MediaType.APPLICATION_JSON)    //用contentType表示具体请求中的媒体类型信息,MediaType.APPLICATION_JSON表示互联网媒体类型的json数据格式(见备注)
  4.             .content(example)  
  5.             .accept(MediaType.APPLICATION_JSON)) //accept指定客户端能够接收的内容类型 
  6.          .andExpect(content().contentType( "application/json;charset=UTF-8")) //验证响应contentType == application/json;charset=UTF-8
  7.          .andExpect(jsonPath( "$.id").value( 1))  //验证id是否为1,jsonPath的使用
  8.             .andExpect(jsonPath( "$.name).value("kqzhu ");  // 验证name是否等于Zhukeqian
  9. String errorExample = "{ "id": 1, "name": "kqzhu"} ";  
  10. MvcResult result = mockMvc.perform(post("/user ")  
  11.         .contentType(MediaType.APPLICATION_JSON)
  12. .content(errorExample)  
  13.         .accept(MediaType.APPLICATION_JSON)) //执行请求  
  14.         .andExpect(status().isBadRequest()) //400错误请求,  status().isOk() 正确  status().isNotFound() 验证控制器不存在
  15.         .andReturn();  //返回MvcResult

Note: Use Content-type to specify the requested information in different formats, a number of content-type of the content format illustrated below in everyday development, often used
    for example: Content-Type: text / html ; charset: utf-8;
 Common media format types are as follows:
    text / HTML: HTML format
    text / plain: plain text format      
    text / xml: XML format /
    Image / GIF: GIF image format    
    image / jpeg: jpg image format 
    image / png: png image format
   begins with application media format type:
   file application / XHTML + XML: XHTML format
   application / xml: XML data format
   application / atom + xml: Atom XML syndication format    
   application / json: JSON data format
   application / pdf: pdf format  
   application / msword: Word document format
   application / octet-stream: the stream of binary data (such as the common file download)
   application / x-www-form- urlencoded: <form encType = ""> the default encType, form form data sent is encoded as a key / value format to the server (the default format of the data submission form)
   Another common medium format is used to upload documents:
    multipart / form-Data: when a file upload is required in the form, it is necessary to use the format

Appendix: identify and explain the Requests & Responses 


Six, ResultMatchers 
        ResultMatcher finished to match the results of the verification request, to which a match (MvcResult result) assertions, if the match fails appropriate exception is thrown, spring mvc framework provides many tests to meet the testing *** ResultMatchers demand.
For details, please Baidu.

Seven, MvcResult
        i.e. the entire execution result obtained after completion of the controller, and not just the return value, which contains all the information required for the test.
MockHttpServletRequest getRequest (): get request execution;
MockHttpServletResponse getResponse (): get the response after execution;
Object the getHandler (): get executed by a processor, is the general controller;
HandlerInterceptor from [] getInterceptors (): get intercept processor interceptors;
ModelAndView getModelAndView (): get ModelAndView after execution;
exception getResolvedException (): get the exception after HandlerExceptionResolver parsed;
FlashMap getFlashMap (): get FlashMap;
Object getAsyncResult () / Object getAsyncResult (Long timeout): to give executed asynchronously the result of;

Information: the most complete history, Spring MVC framework Detailed test - a test server


Original: https://blog.csdn.net/kqZhu/article/details/78836275
 

Guess you like

Origin www.cnblogs.com/jpfss/p/10950904.html