RestTemplate接口测试工具学习
主要用于post接口测试,测试reset风格的接口。
一、创建一个Base类
创建RestTemplate和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 }
二、RestTemplate测试类继承base类
最后执行方法:postForObject(url,params,String.class)会返回方法的返回值。一般都是json格式的返回值
参数:url 要访问的接口方法路径。
params 方法所需要的参数。
String.class 方法的返回类型。

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 }
三、测试的接口
需要注意的是,接口方法的接收参数使用map来接收。需要使用@RequsetBody注解,返回值也是@ResponseBody的json字符串

四、get方式接口测试
测试类接口:用法和post一样,只是路径上的变化,和调用的方法不同
被测试的GET方法,接收参数不需要@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 }
分类:
java
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
2019-04-01 测试管理平台大比拼