Mainly used for post interface testing, test reset style interface.
First, create a class Base
Creating RestTemplate and HttpHeaders
1 package com.tongtech; 2 3 import org.springframework.http.HttpHeaders; 4 import org.springframework.web.client.RestTemplate; 5 6 public class BaseTest { 7 protected static RestTemplate getRestTemplate() { 8 return new RestTemplate(); 9 } 10 11 protected static HttpHeaders createHeaders() { 12 return new HttpHeaders(); 13 } 14 15 protected String getWebRoot(){ 16 return "168.1.37.36:8080/cloud"; 17 } 18 }
Two, RestTemplate test class inherits base class
The last execution method: postForObject (url, params, String.class) returns the method's return value. Usually json format Return value
Parameters: Interface methods url to access the path.
params required method parameters.
String.class return type of the method.
1 package com.tongtech; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 6 import org.junit.Test; 7 import org.springframework.http.HttpHeaders; 8 import org.springframework.http.MediaType; 9 import org.springframework.web.client.RestTemplate; 10 11 public class RestTestDemo extends BaseTest{ 12 13 @Test 14 public void testNodeToPlat() { 15 String url = "http://168.1.37.36:8080/cloud/wbService/largeScreen/nodeMonitor/nodeToPlat"; 16 RestTemplate restTemplate = getRestTemplate(); 17 HttpHeaders headers = createHeaders(); 18 headers.setContentType(MediaType.APPLICATION_JSON); 19 headers.setAccept(MediaType.parseMediaTypes(MediaType.APPLICATION_JSON_VALUE)); 20 Map<String, Object> params = new HashMap<String, Object>(); 21 params.put("level", 213); 22 params.put("platId", "10_16_100"); 23 System.out.println(restTemplate.postForObject(url, params, String.class)); 24 } 25 26 }
Third, the test interface
Note that the reception parameter to an interface method using the received map. @RequsetBody need to use annotations, the return value is @ResponseBody string of json
Four, get way interface testing
Test class interface: usage and post the same, but changes in the path, and a different method calls
GET method to be tested, does not need to receive parameters annotation @RequestBody
1 @Test 2 public void testNodeExchange() { 3 String url = "http://localhost:8080/cloud/wbService/largeScreen/nodeMonitor/list?curPageNum={curPageNum}&completeStatus={completeStatus}"; 4 RestTemplate restTemplate = getRestTemplate(); 5 HttpHeaders headers = createHeaders(); 6 headers.setContentType(MediaType.TEXT_PLAIN); 7 headers.setAccept(MediaType.parseMediaTypes(MediaType.APPLICATION_JSON_VALUE)); 8 Map<String, Object> params = new HashMap<String, Object>(); 9 params.put("curPageNum", 10); 10 params.put("completeStatus", "1"); 11 System.out.println(restTemplate.getForObject(url, String.class, params)); 12 }