SPRINGMVC (5) Resttemplate Control layer Unit test

Source: Internet
Author: User

In front of our web testing, always in the browser, data assembly, request methods, etc. are extremely troublesome.
Resttemplate is a web-tier test template class provided by spring, and we can perform web-layer functional testing at the client's convenience through Resttemplate. It supports restful URLs, and features Annotationmethodhandleradapter data converters Httpmessageconverters assembly capabilities. Resttemplate has helped us to complete the registration of the data converters by default:

    • Bytearrayhttpmessageconverter
    • Stringhttpmessageconverter
    • Resourcehttpmessageconverter
    • Sourcehttpmessageconverter
    • Xmlawareformhttpmessageconverter

By default, we can convert the response data directly using the converters above. And if we like to expand other converters such as Jaxb2rootelementhttpmessageconverter or Mappingjacksonhttpmessageconverter. We can use it setMessageConverters(List<HttpMessageConverter<?>> messageConverters) to register the converters we need.

Using Resttemplate can build a RESTful client request template for us, providing a post, get, put, delete, head, options, Trace, and other request methods, where Our main analysis is to use the post and get methods to simulate our web requests, which has the advantage of being able to programmatically assemble and parse our Web request and response data, as well as to easily modify the request header information.
In the previous article, "SPRINGMVC (4) JSON and object Mutual Transfer Instance resolution request response Data Converter" We intend to test the sending of a JSON format string so that the backend formats the JSON string and translates it into the appropriate JSON object. Which requires contenttype must be application/json. If this request is entered directly from the viewer, it causes the networkerror:415 unsupported Media type error to occur. and using resttemplate can solve this problem and complete our web test conveniently.

Take our previous controller as an example:

@RequestMapping("getUser")publicvoidgetUser( @RequestBody User user){//将输入数据转化为User对象    System.out.println(user);}@ResponseBody//将输出的java对象转换为合适的相应正文输出@RequestMapping("getUser2")publicgetUser2(User user){    System.out.println(user);    return user;}

The first request asks for a JSON format string, Spring automatically converts it to a user object, the second method requires the user member property to be entered as a key-value pair, and then returns the user object directly to spring to the JSON string output.
Here's how we use Resttemplate to request the GetUser method:

Importorg.springframework.http.HttpEntity;ImportOrg.springframework.http.HttpHeaders;ImportOrg.springframework.http.MediaType; Public Static void Main(String args[]) {String user ="{\" id\ ": 10,\" password\ ": \" mypassword\ ", \" username\ ": \" myusername\ "}";//Instance request parametersHttpheaders headers =NewHttpheaders ();//Create a Head object    //Set contenttypeHeaders.setcontenttype (Mediatype.valueof ("Application/json; UTF-8 "));//Set Our request information, the first parameter is the request body, the second parameter is the request header information    //Complete method signature is:httpentity<string> (String body, multivaluemap<string, string> headers)Httpentity<string> strentity =NewHttpentity<string> (user,headers); Resttemplate resttemplate =NewResttemplate ();//Use the Post method to submit the request, the first parameter is the URL, the second parameter is our request information, the third parameter for our corresponding put back data type, and string result to Hall    //The Complete method signature is: Postforobject (String URL, object request, Class<string> Responsetype, Object ... urivariables), The final urivariables is used to expand the content of our request parameters. String result = Resttemplate.postforobject ("Http://localhost:8080/springMVC/user/getUser1", Strentity,string.class); SYSTEM.OUT.PRINTLN (result);//Run method, Output here:    //user [id=10, Username=myusername, Password=mypassword]}

Above we use the Post method to complete the request, if we want to use the Get method, you can use the following methods
getForObject(String url, Class<T> responseType, Object... urlVariables)
We use placeholders in URLs, and then inject them in Urlvariables, using the object ... Injected sequentially, if we want to inject by name, you can use the following overloaded method:
getForObject(String url, Class<T> responseType, Map urlVariables)
The above example we completed the Application/json media format, the JSON string as the parameters of the request server, and the backend to complete the resolution of the Json->java object. Let's look at one more example of sending normal form parameters:

RestTemplate restTemplate  new RestTemplate();//使用占位符绑定入参,这里使用了按顺序注入,所以占位符的参数名任意//如果使用map注入,则占位符名称需与map中key对应。String result = restTemplate.postForObject("http://localhost:8080/springMVC/user/getUser2?id={1}&password={2}&userName={3}"        ,uEntity,String.class,10,"myPassword","myUserName");System.out.println(result);//输出{"id":10,"userName":"myUserName","password":"myPassword"}

Because the resttemplate default is to assemble the aforementioned 5 data converters, if we want Resttemplate to help us automatically convert the JSON string from the previous example to the user object, it is easy to see the following example:

RestTemplate restTemplate  new RestTemplate();ResponseEntity<User> result = restTemplate.postForEntity("http://localhost:8080/springMVC/user/getUser2?id={1}&password={2}&userName={3}"            ,null,User.class,10,"myPassword","myUserName");System.out.println(result2.getBody());

We only need to change the string return value to user, and define our result type as responseentity, using this method, we can obtain the header of the body header information in addition to the body of our response.

In this chapter, we use Resttemplate to complete the client testing work. However, in standard web development, we do not want to always re-deploy the server after modification and then test on the client. In the next article, we will introduce Untils with resttemplate to test our web tier without relying on the server environment.

SPRINGMVC (5) Resttemplate Control layer Unit 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.