SPRINGMVC Test MOCKMVC

Source: Internet
Author: User
Tags assert locale xpath

From: http://www.cnblogs.com/lyy-2016/p/6122144.html (respect copyright)

SPRINGMVC Test Framework

Based on the restful style of SPRINGMVC testing, we can test the full spring MVC process, from URL requests to controller processing to view rendering.

A Mockmvcbuilder

Mockmvcbuilder is used to construct the Mockmvc constructor, which has two main implementations: Standalonemockmvcbuilder and Defaultmockmvcbuilder, respectively, corresponding to two test methods, That is, the standalone installation and integration of the Web environment test (which does not integrate a real web environment, but is simulated by the appropriate mock API, without the need to start the server). For us, we can create it directly using the static factory mockmvcbuilders.

1. Integrated Web Environment approach

Mockmvcbuilders.webappcontextsetup (Webapplicationcontext context): Specify Webapplicationcontext, The corresponding controller is obtained from the context and the corresponding MOCKMVC is obtained;

@RunWith (Springjunit4classrunner.class) @ContextConfiguration ("classpath:config/ Incotermsrestservicetest-context.xml ") @WebAppConfigurationpublic class Incotermsrestservicetest {    @Autowired    private Webapplicationcontext WAC;    Private Mockmvc Mockmvc;    @Before Public    Void Setup () {        This.mockmvc = Mockmvcbuilders.webappcontextsetup (THIS.WAC). build ();   Construct Mockmvc    }    ...}

Attention:
(1) @WebAppConfiguration: The test environment is used to indicate that the applicationcontext used by the test environment will be of type Webapplicationcontext; value specifies the root of the Web application;
(2) through @autowired Webapplicationcontext WAC: Inject the ApplicationContext container of the web environment;
(3) Then create a MOCKMVC by Mockmvcbuilders.webappcontextsetup (WAC). Build () to test;

2. Independent test method

Mockmvcbuilders.standalonesetup (Object ... controllers): Specify a set of controllers by parameters so that they do not need to be obtained from the context;

public class Pricingexportresultsrestservicetest {    @InjectMocks    private Pricingexportresultsrestservice Pricingexportresultsrestservice;    @Mock    private Exportratescheduleservice exportratescheduleservice;    @Mock    private Pricingurlprovider pricingurlprovider;    Private Mockmvc Mockmvc;    @Before Public    Void Setup () {        mockitoannotations.initmocks (this);        MOCKMVC = Mockmvcbuilders.standalonesetup (pricingexportresultsrestservice). build ();  Construct Mockmvc    }    ...}

The main is two steps:
(1) First create the corresponding controller, inject the corresponding dependence
(2) Simulate an MVC test environment through Mockmvcbuilders.standalonesetup, build to get a MOCKMVC

Two MOCKMVC

Let's look at a test example 1:

  @Test public void Createincotermsuccess () throws Exception {Incotermto createdincoterm = new Incotermto ();        Createdincoterm.setid (New Incotermid (uuid.fromstring ("6305ff33-295e-11e5-ae37-54ee7534021a"));        Createdincoterm.setcode ("EXW");        Createdincoterm.setdescription ("code EXW");        Createdincoterm.setlocationqualifier (locationqualifier.departure);        When (Inventoryservice.create (Incotermto.class)). Thenreturn (Createdincoterm); Mockmvc.perform (Post ("/secured/resources/incoterms/create"). Accept (Mediatype.application_json). ContentType ( Mediatype.application_json). Content ("{\" code\ ": \" exw\ ", \" description\ ": \" code exw\ ", \" Locationqualif                Ier\ ": \" Departure\ "}". GetBytes ()))//.anddo (print ()). Andexpect (Status (). IsOk ()) . Andexpect (JsonPath ("Id.value"). Exists ()). Andexpect (JsonPath ("Id.value"). Value ("6305ff33-295e-11e5-a e37-54ee7534021a ")). AndexpecT (JsonPath ("code"). Value ("EXW")); }

Perform: Performs a requestbuilder request, automatically executes the SPRINGMVC process and maps to the appropriate controller execution processing;
Andexpect: Add resultmatcher validation Rules to verify that the results are correct after the controller executes;
Anddo: Add Resulthandler result processor, such as print results to the console when debugging;
Andreturn: Finally, the corresponding Mvcresult is returned, then the custom validation/next asynchronous processing is performed;

See a concrete example of 2:

    @Test public      void TestView () throws Exception {          Mvcresult result = Mockmvc.perform (Mockmvcrequestbuilders.get ( "/USER/1"))                  . Andexpect (Mockmvcresultmatchers.view (). Name ("User/view"))                  . Andexpect ( Mockmvcresultmatchers.model (). Attributeexists ("user"))                  . Anddo (Mockmvcresulthandlers.print ())                  . Andreturn ();                    Assert.assertnotnull (Result.getmodelandview (). Getmodel (). Get ("user"));        

The whole process:
1, Mockmvc.perform to execute a request;
2, Mockmvcrequestbuilders.get ("/USER/1") constructs a request
3. Resultactions.andexpect add assertion after completion of execution
4. Resultactions.anddo Adds a result handler that indicates what to do with the result, such as using Mockmvcresulthandlers.print () to output the entire response result information here.
5. Resultactions.andreturn indicates that the corresponding result is returned when the execution is complete.

The whole test process is very regular:
1. Prepare the test environment
2. Execute request through MOCKMVC
3.1. Adding validation assertions
3.2. Add result processor
3.3. Get Mvcresult to make a custom assertion/make the next asynchronous request
4. Unloading test environment

Three Requestbuilder/mockmvcrequestbuilders

As you can see from the name, Requestbuilder is used to build the request, which provides a way for buildrequest (ServletContext ServletContext) to build Mockhttpservletrequest There are mainly two subcategories of Mockhttpservletrequestbuilder and Mockmultiparthttpservletrequestbuilder (such as file uploads), which are used to mock all the data required by the client request.

1.MockMvcRequestBuilders Main API

Mockhttpservletrequestbuilder Get (String urltemplate, Object ... urlvariables) : According to URI template and URI variable is worth a GET request way of mockhttpservletrequestbuilder, such as Get (/user/{id}, 1L);
Mockhttpservletrequestbuilder Post (string urltemplate, Object ... urlvariables): Similar to get, but is the post method;
Mockhttpservletrequestbuilder put (string Urltemplate, Object ... urlvariables): Similar to get, but is put method;
Mockhttpservletrequestbuilder Delete (String urltemplate, Object ... urlvariables): Similar to get, but is the Delete method;
Mockhttpservletrequestbuilder options (String urltemplate, Object ... Urlvariables): Similar to get, but is the options method;
Mockhttpservletrequestbuilder request (HttpMethod HttpMethod, String Urltemplate, Object ... urlvariables): provides its own HTTP request method and URI template and URI variable, as the above API is delegated to this API;
Mockmultiparthttpservletrequestbuilder fileUpload (String urltemplate, Object ... urlvariables): Provides a request for file upload method, Get Mockmultiparthttpservletrequestbuilder;
Requestbuilder asyncdispatch (final Mvcresult Mvcresult) : Creates a requestbuilder that asynchronously dispatches from the Mvcresult that initiates the asynchronous processing of the request;

2.MockHttpServletRequestBuilder and Mockmultiparthttpservletrequestbuilder API

(1) Mockhttpservletrequestbuilder API

Mockhttpservletrequestbuilder Header (String name, Object ... values)/mockhttpservletrequestbuilder headers ( Httpheaders httpheaders): Add header information;
Mockhttpservletrequestbuilder ContentType (mediatype mediatype): Specifies the requested ContentType header information;
Mockhttpservletrequestbuilder Accept (mediatype ... mediatypes)/mockhttpservletrequestbuilder Accept (String ... MediaTypes): Specifies the requested accept header information;
Mockhttpservletrequestbuilder content (byte[] content)/mockhttpservletrequestbuilder content (String content) : Specifies the content of the request body body;
Mockhttpservletrequestbuilder Cookies (Cookies ... cookies): Specify the requested cookie;
Mockhttpservletrequestbuilder locale (locale locale): Specifies the requested locale;
Mockhttpservletrequestbuilder characterencoding (String encoding): Specifies the request character encoding;
Mockhttpservletrequestbuilder requestattr (String name, Object value): Sets the request property data;
Mockhttpservletrequestbuilder sessionattr (String name, Object value)/mockhttpservletrequestbuilder sessionattrs (Map <string, object= "" > Sessionattributes): Set the request session property data;
Mockhttpservletrequestbuilder flashattr (String name, Object value)/mockhttpservletrequestbuilder flashattrs (Map< String, object= "" > Flashattributes): Specifies the requested flash information, such as the redirected attribute information;
Mockhttpservletrequestbuilder session (mockhttpsession session): Specifies the session of the request;
Mockhttpservletrequestbuilder Principal (principal principal): Specifies the requested principal;
Mockhttpservletrequestbuilder ContextPath (String contextpath): Specifies the requested context path, which must start with "/" and cannot end with "/";
Mockhttpservletrequestbuilder PathInfo (String pathInfo): The requested path information must begin with "/";
Mockhttpservletrequestbuilder Secure: Request whether to use a secure channel;
Mockhttpservletrequestbuilder with (Requestpostprocessor postprocessor): The post-processor of the request, which is used to customize the extension points of some request processing;

(2) Mockmultiparthttpservletrequestbuilder inherits from Mockhttpservletrequestbuilder, and provides the following API

Mockmultiparthttpservletrequestbuilder file (String name, byte[] content)/mockmultiparthttpservletrequestbuilder File (mockmultipartfile): Specifies the files to be uploaded;

Four resultactions

After calling Mockmvc.perform (Requestbuilder requestbuilder), you will get resultactions and complete the following three things through Resultactions:
Resultactions Andexpect (resultmatcher matcher): Adds a validation assertion to determine whether the result after the request is executed is expected;
Resultactions Anddo (Resulthandler handler): Adds a result processor for actions performed after validation succeeds, such as output under request/result information for debugging;
Mvcresult Andreturn (): Returns the Mvcresult after successful validation, asynchronous processing for custom validation/next;

Five Resultmatcher/mockmvcresultmatchers

The 1.ResultMatcher is used to match the result validation after execution of the request, which is a match (mvcresult result) assertion method and throws the corresponding exception if the match fails; the Spring MVC Test Framework provides a lot of * * * Resultmatchers to meet testing needs. Note that these ***resultmatchers are not resultmatcher subclasses, but instead return to the Resultmatcher instance. The Spring MVC Test Framework provides mockmvcresultmatchers static factory methods for easy testing and easy operation.

2. The specific API is as follows:
Handlerresultmatchers handler (): The requested handler validator, such as verifying the processor type/method name; Here the handler is actually the controller that handles the request;
Requestresultmatchers request (): Get Requestresultmatchers authenticator;
Modelresultmatchers model (): To obtain models validator;
Viewresultmatchers view (): Get the viewer validator;
Flashattributeresultmatchers Flash (): Get the Flash property validation;
Statusresultmatchers status (): Gets the response status validator;
Headerresultmatchers header (): Gets the response header validator;
Cookieresultmatchers Cookie (): Gets the response cookie validator;
Contentresultmatchers content (): Get the response contents validator;
Jsonpathresultmatchers JsonPath (string expression, Object ... args)/resultmatcher JsonPath (string expression, Matcher Matcher): Get JSON expression validator;
Xpathresultmatchers XPath (string expression, Object ... args)/xpathresultmatchers XPath (string expression, map< String, string= "" > Namespaces, Object ... args): Gets an XPath expression validator;
Resultmatcher Forwardedurl (Final String expectedurl): Verifies the URL that is forwarded after processing the request (absolute match);
Resultmatcher Forwardedurlpattern (Final String Urlpattern): Validates the URL that is forwarded after processing the request (Ant-style pattern matching, @since Spring4);
Resultmatcher Redirectedurl (Final String expectedurl): Verifies the URL that was redirected after processing the request (absolute match);
Resultmatcher Redirectedurlpattern (Final String expectedurl): Verifies the URL that was redirected after processing the request (Ant-style pattern match, @since Spring4);

Six commonly used tests

1. Test the general controller

Mockmvc.perform (Get ("/user/{id}", 1))//Execute request              . Andexpect (Model (). Attributeexists ("user"))//Validate storage model data              . Andexpect (view (). Name ("User/view"))//Verify ViewName              . Andexpect (Forwardedurl ("/web-inf/jsp/user/view.jsp"))// Validates the JSP that forward to when the view is rendered              . Andexpect (Status (). IsOk ())//Verify status Code              . Anddo (print ());//Output Mvcresult to the console

2. Get Mvcresult Custom Validation

Mvcresult result = Mockmvc.perform (Get ("/user/{id}", 1)//executes the request          . Andreturn ();//Return to Mvcresult  Assert.assertnotnull (Result.getmodelandview (). Getmodel (). Get ("user")); Custom assertions   

3. Verify that the request parameters are bound to the model data and Flash properties

Mockmvc.perform ("/user"). Param ("name", "Zhang")//Perform a POST request for passing parameters (also post ("/user?name=zhang"))              . Andexpect (Handler (). Handlertype (Usercontroller.class))//Verify the type of controller being executed              . Andexpect (Handler (). MethodName ("Create "))//Verify the name of the controller method being executed              . Andexpect (Model (). Hasnoerrors ())//Verify that the page has no errors              . Andexpect (Flash (). Attributeexists (" Success "))//Verify that there is a Flash attribute              . Andexpect (View (). Name (" Redirect:/user "));//Verify View  

4. File Upload

byte[] bytes = new byte[] {1, 2};  Mockmvc.perform ("FileUpload" ("/user/{id}/icon", 1L). File ("icon", bytes))//Perform a document upload          . Andexpect (Model (). Attribute ( "Icon", bytes))//Verify attribute Equality          . Andexpect (View (). Name ("Success"));//Verify View  

5.JSON Request/Response Verification

String requestbody = "{\" id\ ": 1, \" name\ ": \" zhang\ "}";      Mockmvc.perform (Post ("/user")              . ContentType (Mediatype.application_json). Content (Requestbody)              . Accept ( Mediatype.application_json))//Execute request              . Andexpect (Content (). ContentType (Mediatype.application_json))// Verify the response contenttype              . Andexpect (JsonPath ("$.id"). Value (1));//Use JSON path to verify JSON refer to the http://goessner.net/articles/ jsonpath/            String errorbody = "{id:1, Name:zhang}";      Mvcresult result = Mockmvc.perform (post ("/user")              . ContentType (Mediatype.application_json). Content (Errorbody)              . Accept (Mediatype.application_json))//Execute request              . Andexpect (Status (). Isbadrequest ())//400 error request              . Andreturn ();            Assert.asserttrue (HttpMessageNotReadableException.class.isAssignableFrom (Result.getresolvedexception (). GetClass ()));//Wrong request content body

6. Asynchronous Testing

Callable      Mvcresult result = Mockmvc.perform (Get ("/user/async1?id=1&name=zhang"))//Execute request              . Andexpect ( Request (). asyncstarted ())              . Andexpect (Request (). AsyncResult (Corematchers.instanceof (User.class)))// The default is to wait 10 seconds to time out              . Andreturn ();            Mockmvc.perform (Asyncdispatch (Result))              . Andexpect (Status (). IsOk ())              . Andexpect (Content (). ContentType ( Mediatype.application_json)              . Andexpect (JsonPath ("$.id"). Value (1));  

7. Global Configuration

MOCKMVC = Webappcontextsetup (WAC)              . Defaultrequest (Get ("/USER/1"). Requestattr ("Default", True)//default request If it is of type mergeable, it is automatically merged with the Requestbuilder              . ALWAYSDO (print ())  //The action that is done after each request is performed by the Mockmvc.perform.              Alwaysexpect (Request (). Attribute ("Default", True)//the assertion that the default is validated after each execution              . Build ();            Mockmvc.perform (Get ("/USER/1"))              . Andexpect (Model (). Attributeexists ("user"));  

SPRINGMVC Test MOCKMVC

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.