(Take Doctrine-9) Spring Boot builds RESTful APIs and unit tests (iv)

Source: Internet
Author: User

    • @Controller: Modifier class, used to create an object that handles HTTP requests
    • @RestController: Spring4 added after the annotation, the original in the @Controller return JSON needs @ResponseBody to mate, if directly with the @RestController substitution @Controller will not need to configure @ResponseBody , the default return JSON format.
    • @RequestMapping: Configure URL Mappings

Below we try to use spring MVC to implement a set of restful APIs for user object operations, with comments detailing how HTTP requests are mapped in spring MVC, how to pass the parameters, and how to write unit tests.

The RESTful API is specifically designed as follows:

User Entity definition:

 Public class User {      private  Long ID;      Private String name;      Private Integer age;       //      }


Implementing an interface for manipulating user objects

1 @RestController2@RequestMapping (value= "/users")//with this configuration, the following mappings are under/users3  Public classUsercontroller {4  5     //Create a thread-safe map6     StaticMap<long, user> users = Collections.synchronizedmap (NewHashmap<long, user>()); 7  8@RequestMapping (value= "/", method=requestmethod.get)9      PublicList<user>getuserlist () {Ten         //GET request to handle "/users/" to get the list of users One         //You can also use @requestparam to pass parameters from the page to query conditions or to transfer page information. Alist<user> r =NewArraylist<user>(Users.values ()); -         returnR; -     }  the   -@RequestMapping (value= "/", method=requestmethod.post) -      PublicString postuser (@ModelAttribute user user) { -         //a POST request that handles "/users/" to create a user +         //In addition to the @modelattribute binding parameters, you can also pass parameters from the page by @requestparam - Users.put (User.getid (), user); +         return"Success";  A     }  at   -@RequestMapping (value= "/{id}", method=requestmethod.get) -      PublicUser getUser (@PathVariable Long id) { -         //GET request to process "/users/{id}" to get user information for ID value in URL -         //the ID in the URL can be bound to the parameters of the function by @pathvariable -         returnusers.get (ID); in     }  -   to@RequestMapping (value= "/{id}", method=requestmethod.put) +      PublicString putuser (@PathVariable Long ID, @ModelAttribute user user) { -         //handle put request for "/users/{id}" to update user information theUser U =users.get (ID); * U.setname (User.getname ()); $ U.setage (User.getage ());Panax Notoginseng users.put (ID, u); -         return"Success";  the     }  +   A@RequestMapping (value= "/{id}", method=requestmethod.delete) the      PublicString deleteuser (@PathVariable Long id) { +         //Delete request to process "/users/{id}" to delete user - users.remove (ID); $         return"Success";  $     }  -   -}

The following test case validation correctness is written for the controller, as follows. Of course, the browser plug-in can also be used to submit validation requests.

1 2 3 ImportOrg.junit.Before;4 Importorg.junit.Test;5 ImportOrg.junit.runner.RunWith;6 Importorg.springframework.boot.test.context.SpringBootTest;7 ImportOrg.springframework.test.context.junit4.SpringJUnit4ClassRunner;8 Importorg.springframework.test.context.web.WebAppConfiguration;9 ImportORG.SPRINGFRAMEWORK.TEST.WEB.SERVLET.MOCKMVC;Ten ImportOrg.springframework.test.web.servlet.RequestBuilder; One Importorg.springframework.test.web.servlet.setup.MockMvcBuilders; A  - Import StaticOrg.hamcrest.Matchers.equalTo; - Import Staticorg.springframework.test.web.servlet.request.mockmvcrequestbuilders.*; the Import Staticorg.springframework.test.web.servlet.result.MockMvcResultMatchers.content; - Import StaticOrg.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -  -@RunWith (Springjunit4classrunner.class) + @SpringBootTest - @WebAppConfiguration +  Public classApplicationtest { A  at     PrivateMOCKMVC MVC; -  - @Before -      Public voidSetUp ()throwsException { -MVC = Mockmvcbuilders.standalonesetup (NewUsercontroller ()). build (); -     } in  - @Test to      Public voidTestusercontroller ()throwsException { +         //Test Usercontroller -Requestbuilder request =NULL; the  *         //1, get check the user list, should be empty $Request = Get ("/users/");Panax Notoginseng mvc.perform (Request) - . Andexpect (Status (). IsOk ()) the. Andexpect (Content (). String (Equalto ("[]"))); +  A         //2. Post submits a user theRequest = post ("/users/") +. PARAM ("id", "1") -. param ("name", "Test Master") $. param ("Age", "20"); $ mvc.perform (Request) -. Andexpect (Content (). String (Equalto ("Success"))); -  the         //3, get get the user list, should have just inserted data -Request = Get ("/users/");Wuyi mvc.perform (Request) the . Andexpect (Status (). IsOk ()) -. Andexpect (Content (). String (Equalto ("[{\" id\ ": 1,\" name\ ": \" Test master \ ", \" age\ ": 20}]"))); Wu  -         //4, put modify the user ID 1 AboutRequest = put ("/USERS/1") $. param ("name", "Ultimate Test Master") -. param ("Age", "30"); - mvc.perform (Request) -. Andexpect (Content (). String (Equalto ("Success"))); A  +         //5, get an ID of 1 user theRequest = Get ("/USERS/1"); - mvc.perform (Request) $. Andexpect (Content (). String (Equalto ("{\" id\ ": 1,\" name\ ": \" test Ultimate master \ ", \" age\ ": 30}"))); the  the         //6. Del Delete user with ID 1 theRequest = Delete ("/USERS/1"); the mvc.perform (Request) -. Andexpect (Content (). String (Equalto ("Success"))); in  the         //7, get check the user list, should be empty theRequest = Get ("/users/"); About mvc.perform (Request) the . Andexpect (Status (). IsOk ()) the. Andexpect (Content (). String (Equalto ("[]"))); the  +     } -  the}


At this point, by introducing a Web module (without any other configuration), we can easily take advantage of the functionality of Spring MVC and complete the creation of a restful API for user objects and the writing of unit tests with very simple code. It also introduces some of the most commonly used core annotations in spring MVC:, @Controller @RestController RequestMapping as well as some parameter binding annotations: @PathVariable ,, and @ModelAttribute @RequestParam so on.

(Take Doctrine-9) Spring Boot builds RESTful APIs and unit tests (iv)

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.