SpringMVC4 (5) Resttemplate Control layer Unit test

Source: Internet
Author: User

In front of our web test, always in the browser. Data assembly, request method, etc. are extremely troublesome.


Resttemplate is a web-based test template class provided by spring, and we are able to test the Web layer function conveniently through resttemplate in the client. It supports restful URLs and has the annotationmethodhandleradapter of httpmessageconverters for data converters.

Resttemplate has helped us through by default. The Data Converter Register:

    • Bytearrayhttpmessageconverter
    • Stringhttpmessageconverter
    • Resourcehttpmessageconverter
    • Sourcehttpmessageconverter
    • Xmlawareformhttpmessageconverter

In the default case. We are able to convert the response data directly using the converters above.

Suppose, however, that we like to expand other converters such as Jaxb2rootelementhttpmessageconverter or Mappingjacksonhttpmessageconverter. We are able to 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, and at the same time can easily change 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 corresponding JSON object. The requirement of contenttype must be Application/json.

Assuming that this request is entered directly from the viewer, it causes the networkerror:415 unsupported Media type error to occur.

And the use of resttemplate can solve the problem and the convenience of the completion of our Web test.

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 requires a JSON format string to be entered. Spring takes its own initiative to convert it to a user object, and the second method requires the user member property to be entered as a key-value pair, which is then returned directly to the user object, which is converted to the JSON string output by spring.
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 number is the URL, the second parameter is our request information, and the third parameter returns the data type for our correspondence. With the string result to the hall    //The Complete method signature is: Postforobject (String URL, object request, Class<string> Responsetype, Object ... urivariables), The final urivariables is used to expand our request for a number of content.

String result = restTemplate.postForObject("http://localhost:8080/springMVC/user/getUser1",strEntity,String.class); System.out.println(result);//执行方法,这里输出: //User [id=10, userName=myUserName, password=myPassword]}

Above we use the Post method to complete the request, assuming we want to use the Get method 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 ... Inject in order, assuming we want to inject by name. You can use the following overloaded methods, for example:
getForObject(String url, Class<T> responseType, Map urlVariables)
We're done with the above example. Request server in Application/json Media format, JSON string, and parse the Json->java object at the back end. Let's look at a sample that sends a normal form parameter:

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"}

Since resttemplate is the default assembly of the 5 data converters mentioned earlier. Let's say we want resttemplate to help us convert the JSON string from the previous example to the user object itself. It is also very easy to see the following demo examples:

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 the type of our result as responseentity, and we can use this method. In addition to being able to get our response body body, we were able to get to the header of the body headers.

In this chapter. We finished the client test work using Resttemplate. But in standard web development. We don't want to always deploy the server again after the change, and then try again on the client.

In the next article. Will introduce Untils with resttemplate to test our web tier without relying on the server environment.

SpringMVC4 (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.