JUNIT4 Unit Test--web project to simulate login session, do full process test

Source: Internet
Author: User

JUNIT4 writes unit test cases in the annotation-based way relative to Junit3, which is much easier to use. The following abbreviations are snippets of code, excerpts of which are key parts, it is important to understand the knowledge points.

First, write the test case base class

@RunWith (Springjunit4classrunner.class) @WebAppConfiguration @contextconfiguration ({"File:src/main/webapp/web-inf/applicationcontext.xml", "File:src/main/webapp/web-inf/spring-servlet.xml",    "File:src/main/webapp/web-inf/conf/spring-redis.xml", "file:src/main/webapp/web-inf/conf/ Spring-resttemplate.xml "}) Public Abstract classbasejunit{/*** WAC*/@AutowiredPrivateWebapplicationcontext WAC; /*** MOCKMVC*/    PrivateMockmvc Mockmvc; protectedWebapplicationcontext GETWAC () {return  This. WAC; }    protectedMockmvc Getmockmvc () {return  This. Mockmvc; }    /*** Initialize MOCMVC * *@see     */@Before Public voidsetUp () { This. Mockmvc = Webappcontextsetup ( This. WAC). build (); }

......}
@RunWith (Springjunit4classrunner.class)  specifies that the runtime environment of spring be used @webappconfiguration  Used to declare that this is a Web test environment @contextconfiguration used to specify the configuration file to load the project

Second, pull out the Web system login method
 Public Abstract classBaseloginjunitextendsbasejunit{/*** MOCKMVC*/    Privatemockhttpsession session; protectedmockhttpsession getsession () {returnsession; }    /*** Before testing, initialize the system login * *@see     */@Before Public voidsetUp () {Super. SetUp ();  This. session =(mockhttpsession) getloginsession (); }    /*** Complete login function, return to current login session * *@returnHttpSession *@see     */    PrivateHttpSession getloginsession () {String URL= "/xxx/login"; String params= "{\" username\ ": \" xxx\ ", \" password\ ": \" xxx\ ", \" verifycode\ ": \" xxx\ "}"; Mvcresult result=NULL; Try{result=Getmockmvc (). Perform (Mockmvcrequestbuilders.post (URL). Accept (Mediatype.application_json). ContentType ( Mediatype.application_json_utf8_value). Content (params)). Andexpect (Mockmvcresultmatchers.status (). IsOk (        ). Anddo (Mockmvcresulthandlers.print ()). Andreturn (); }        Catch(Exception e) {e.printstacktrace (); }        returnresult.getrequest (). GetSession (); }

......}

Third, write the Spring controller test method

@FixMethodOrder (methodsorters.name_ascending)//Specifies that test cases are executed in alphabetical order Public classResourcecontrollertestextendsbaseloginjunit{/*** Res ID list*/    Private StaticList<string> res_list =NewArraylist<>(); /*** Test getresource * *@see     */@Test Public voidTestgetresource () {String URL= "/xxx/get"; Multivaluemap<string, string> map =NewLinkedmultivaluemap<>();  This. Setpage (map);    Get (URL, map); }    /*** Test Add * *@see     */@Test Public voidTestaddresource () {String URL= "/xxx/add"; Resourcebean Bean=NewResourcebean (); Resourcebean Anotherbean=NewResourcebean (); Bean.setresname ("Test Res1"); Anotherbean.setresname ("Test Res2"); Mvcresult result=post (URL, jsonobject.tojsonstring (bean)); ReturnVal ReturnVal= This. Getreturnval (Result);        Res_list.add (Returnval.getdata (). GetId ()); Mvcresult Anotherresult=post (URL, jsonobject.tojsonstring (Childbean)); ReturnVal Anotherreturnval= This. Getreturnval (Anotherresult);    Res_list.add (Anotherreturnval.getdata (). GetId ()); }    /*** Test Updateresource * *@see     */@Test Public voidTestbupdateresource () {String URL= "/xxx/update"; Resourcebean Bean=NewResourcebean (); Bean.setid (Res_list.get (0)); Bean.setresname ("Test Res1"); Mvcresult result=post (URL, jsonobject.tojsonstring (bean));    Assertequals (abstractcontroller.status_success, Getreturnval (Result). GetStatus ()); }    /*** Test Delresource * *@see     */@Test Public voidTestcdelresource () {String URL= "/xxx/delete"; Multivaluemap<string, string> map =NewLinkedmultivaluemap<>(); Map.add ("id", Res_list.get (0)); Mvcresult result=get (URL, map);    Assertequals (abstractcontroller.status_success, Getreturnval (Result). GetStatus ()); }    /*** Test Batchdelresource * *@see     */@Test Public voidTestdbatchdelresource () {String URL= "/xxx/batchdel"; Multivaluemap<string, string> map =NewLinkedmultivaluemap<>(); StringBuilder params=NewStringBuilder ();  for(inti = 0; I < res_list.size (); i++ )        {            if(i = = Res_list.size ()-1) {params.append (Res_list.get (i)); }            Else{params.append (Res_list.get (i)). Append (","); }} map.add ("id", params.tostring ()); Mvcresult result=get (URL, map);    Assertequals (abstractcontroller.status_success, Getreturnval (Result). GetStatus ()); }}

In the above test cases, the @FixMethodOrder is critical because the order of tests needs to be specified for adding, deleting, changing, and checking. methodsorters.name_ascending specifies that the test case be executed alphabetically, with the first letter after test followed by a, B, C, D. In JUnit, there are three choices for the value of @FixMethodOrder, as follows:

Methodsorters.default: In the default order, the exact order is indeterminate.

METHODSORTERS.JVM: The order of the methods obtained by the JVM.

Methodsorters.name_ascending: in alphabetical order.

In use cases, the test cases need to be executed in the specified order, using METHODSORTERS.JVM in the test, which explains that this is performed in the order of the methods in the method, and the actual test is not practicable. Final selection methodsorters.name_ascending in alphabetical order. Several use cases involve the problem of data dependency, where the dependent data is put into static res_list for sharing by the parties.

Ps:

1, the use of the process, using Setup to initialize the login, and JUnit in each test case before execution, will call the Setup method, causing the login function to call frequently, in fact, just call once. The problem remains to be solved. However, according to the above method, from the simulation login, to the specified test process can be carried out, the general test can be satisfied.

2, described here is only the controller part of the test, just test the HTTP request.

The above is a little record in the project, you have better suggestions, welcome to shoot bricks.

JUNIT4 Unit Test--web project to simulate login session, do full process 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.