How Spring MVC tests the controller (using SPRINGMVC Mock test)

Source: Internet
Author: User
Tags assert

The general test cases in SPRINGMVC are test service tiers, and today I'll show you how to test the controller layer code directly using SPRINGMVC mock.

1. What is a mock test?

A mock test is a test method that is created in order to be tested with a virtual object for some objects that are not easily constructed or are not easily accessible during the test process.

2. Why use mock testing?

Test with mock Object, It is primarily used to simulate tools that are not easily constructed in the application (such as HttpServletRequest must be constructed in a servlet container) or more complex objects (such as ResultSet objects in JDBC) to make the test run smoothly.

3. Common annotations

Runwith (springjunit4classrunner.class): Indicates unit testing using the Spring test component;

Webappconfiguratio: Using this annotation will actually start a Web service during the run unit test and then begin invoking the controller's rest API to stop the Web service after the unit test runs.

Contextconfiguration: Specify the bean profile information can be in several ways, this example uses the file path form, if there are multiple configuration files, you can configure the information in parentheses as a string array to represent;

4. Install the test environment
The Spring MVC Test Framework provides two ways to install and integrate Web environment tests independently (this approach does not integrate a real web environment, but rather simulates testing with the appropriate mock API without starting the server).

    • Independent installation 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;

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

The code is as follows:

 Packagecom.xfs.test;ImportOrg.junit.Assert;ImportOrg.junit.Before;Importorg.junit.Test;ImportORG.SPRINGFRAMEWORK.TEST.WEB.SERVLET.MOCKMVC;ImportOrg.springframework.test.web.servlet.MvcResult;Importorg.springframework.test.web.servlet.request.MockMvcRequestBuilders;Importorg.springframework.test.web.servlet.result.MockMvcResultHandlers;Importorg.springframework.test.web.servlet.result.MockMvcResultMatchers;Importorg.springframework.test.web.servlet.setup.MockMvcBuilders;ImportCom.alibaba.fastjson.JSON;ImportCom.alibaba.fastjson.JSONObject;ImportCom.xfs.web.controller.APIController;/*** Standalone installation test mode SPRINGMVC Mock Test * *@authorAdmin * * November 23, 2017 morning 10:39:49*/ Public classTestapione {PrivateMockmvc Mockmvc; @Before Public voidsetUp () {Apicontroller Apicontroller=NewApicontroller (); Mockmvc=Mockmvcbuilders.standalonesetup (Apicontroller). build (); } @Test Public voidtestgetsequence () {Try{Mvcresult Mvcresult= Mockmvc.perform (Mockmvcrequestbuilders.post ("/api/getsequence"). Andexpect (Mockmvcresultmatchers.status (). Is (200). Anddo (Mockmvcresulthandlers.print ()). Andreturn (); intStatus =mvcresult.getresponse (). GetStatus (); System.out.println ("Request Status Code:" +status); String result=mvcresult.getresponse (). getcontentasstring (); System.out.println ("Interface Returns the result:" +result); Jsonobject Resultobj=json.parseobject (Result); //determines whether the interface returns the Success field in JSON as trueAssert.asserttrue (Resultobj.getbooleanvalue ("Success")); } Catch(Exception e) {e.printstacktrace (); }    }}

The request results are as follows:

    • Integrated Web Environment approach

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

The main is three steps:

(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 App
(2) via @autowired webapplicationcontext WAC: ApplicationContext container injected into the web environment
(3) Then create a MOCKMVC by Mockmvcbuilders.webappcontextsetup (WAC). Build () to test

The code is as follows:

 Packagecom.xfs.test;ImportOrg.junit.Assert;ImportOrg.junit.Before;Importorg.junit.Test;ImportOrg.junit.runner.RunWith;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.mock.web.MockHttpSession;Importorg.springframework.test.context.ContextConfiguration;Importorg.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;Importorg.springframework.test.context.web.WebAppConfiguration;ImportORG.SPRINGFRAMEWORK.TEST.WEB.SERVLET.MOCKMVC;ImportOrg.springframework.test.web.servlet.MvcResult;Importorg.springframework.test.web.servlet.request.MockMvcRequestBuilders;Importorg.springframework.test.web.servlet.result.MockMvcResultHandlers;Importorg.springframework.test.web.servlet.result.MockMvcResultMatchers;Importorg.springframework.test.web.servlet.setup.MockMvcBuilders;ImportOrg.springframework.web.context.WebApplicationContext;ImportCom.alibaba.fastjson.JSON;ImportCom.alibaba.fastjson.JSONObject;/*** Integrated Web Environment Mode SPRINGMVC Mock Test * *@authorAdmin * * November 23, 2017 morning 11:12:43*/@RunWith (Junit4classrunner.class) @WebAppConfiguration @contextconfiguration (Locations= {"Classpath*:spring/*.xml" }) Public classTestapitwoextendsabstractjunit4springcontexttests {@Autowired PublicWebapplicationcontext WAC;  PublicMockmvc Mockmvc;  Publicmockhttpsession session; @Before Public voidBefore ()throwsException {Mockmvc=Mockmvcbuilders.webappcontextsetup (WAC). build (); } @Test Public voidtestgetsequence () {Try{Mvcresult Mvcresult= Mockmvc.perform (Mockmvcrequestbuilders.post ("/api/getsequence"). Andexpect (Mockmvcresultmatchers.status (). Is (200). Anddo (Mockmvcresulthandlers.print ()). Andreturn (); intStatus =mvcresult.getresponse (). GetStatus (); System.out.println ("Request Status Code:" +status); String result=mvcresult.getresponse (). getcontentasstring (); System.out.println ("Interface Returns the result:" +result); Jsonobject Resultobj=json.parseobject (Result); //determines whether the interface returns the Success field in JSON as trueAssert.asserttrue (Resultobj.getbooleanvalue ("Success")); } Catch(Exception e) {e.printstacktrace (); }    }}

The result is the same as the above independent test.

Summarize:


1. Mockmvc.perform executes a request;
2, mockmvcrequestbuilders.get ("/USER/1") constructs a request

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 means that the result is returned when execution is complete.

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

Reference:

https://docs.spring.io/spring/docs/4.0.0.RELEASE/spring-framework-reference/htmlsingle/#spring-mvc-test-framework

How Spring MVC tests the controller (using SPRINGMVC Mock test)

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.