spring boot中使用json进行http请求单元测试
创始人
2024-05-26 11:16:12
0

1、配置文件存放

resource/properties/demo.json

{"desc": "spring boot property config of json file","babbys": [{"name": "Tom","age": 2,"address": "苏州"},{"name": "Lily","age": 5,"address": "杭州"}]
}

2、实体对象

import lombok.Data;@Data
public class Demo {private String desc;private List babbys;
}
import lombok.Data;@Data
public class Babby {private String name;private Integer age;private String address;
}

3、配置

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;import java.io.IOException;
import java.io.InputStream;@Configuration
public class JsonFileConfig {@Beanpublic Demo demo() throws IOException {Resource resource = new ClassPathResource("properties/demo.json");InputStream inputStream = resource.getInputStream();return new ObjectMapper().readValue(inputStream, Demo.class);}
}

4、使用

@Autowired
private Demo demo;

5、封装http请求

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;public class HttpClientUtils {private static final Logger logger = LogManager.getLogger(HttpClientUtils.class);/*** 封装POST请求(Map入参)** @param url 请求的路径* @param map 请求的参数* @return* @throws IOException*/public static String post(String url, Map map) throws IOException {
//        1、创建HttpClient对象CloseableHttpClient httpClient = HttpClients.createDefault();
//        2、创建请求方式的实例HttpPost httpPost = new HttpPost();try {httpPost.setURI(new URI(url));} catch (URISyntaxException e) {e.printStackTrace();}
//        3、添加请求参数(设置请求和传输超时时间)RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();httpPost.setConfig(requestConfig);ArrayList list = new ArrayList<>();Set entrySet = map.entrySet();for (Map.Entry entry : entrySet) {String key = entry.getKey().toString();String value = entry.getValue().toString();list.add(new BasicNameValuePair(key, value));}httpPost.setEntity(new UrlEncodedFormEntity(list, org.apache.http.protocol.HTTP.UTF_8));
//        4、发送Http请求HttpResponse response = httpClient.execute(httpPost);
//        5、获取返回的内容String result = null;int statusCode = response.getStatusLine().getStatusCode();if (200 == statusCode) {result = EntityUtils.toString(response.getEntity());} else {logger.info("请求第三方接口出现错误,状态码为:{}", statusCode);return null;}
//        6、释放资源httpPost.abort();httpClient.getConnectionManager().shutdown();return result;}/*** 封装POST请求(String入参)** @param url  请求的路径* @param data String类型数据* @return* @throws IOException*/public static String post(String url, String data) throws IOException {
//        1、创建HttpClient对象HttpClient httpClient = HttpClientBuilder.create().build();
//        2、创建请求方式的实例HttpPost httpPost = new HttpPost(url);
//        3、添加请求参数(设置请求和传输超时时间)RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();httpPost.setConfig(requestConfig);httpPost.setHeader("Accept", "application/json");httpPost.setHeader("Content-Type", "application/json");
//        设置请求参数httpPost.setEntity(new StringEntity(data, "UTF-8"));
//        4、发送Http请求HttpResponse response = httpClient.execute(httpPost);
//        5、获取返回的内容String result = null;int statusCode = response.getStatusLine().getStatusCode();if (200 == statusCode) {result = EntityUtils.toString(response.getEntity());} else {logger.info("请求第三方接口出现错误,状态码为:{}", statusCode);return null;}
//        6、释放资源httpPost.abort();httpClient.getConnectionManager().shutdown();return result;}/*** 封装GET请求** @param url* @return* @throws IOException*/public static String get(String url) throws IOException {
//        1、创建HttpClient对象HttpClient httpClient = HttpClientBuilder.create().build();
//        2、创建请求方式的实例HttpGet httpGet = new HttpGet(url);
//        3、添加请求参数(设置请求和传输超时时间)RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();httpGet.setConfig(requestConfig);
//        4、发送Http请求HttpResponse response = httpClient.execute(httpGet);
//        5、获取返回的内容String result = null;int statusCode = response.getStatusLine().getStatusCode();if (200 == statusCode) {result = EntityUtils.toString(response.getEntity());} else {logger.info("请求第三方接口出现错误,状态码为:{}", statusCode);return null;}
//        6、释放资源httpGet.abort();httpClient.getConnectionManager().shutdown();return result;}
}

6、单元测试

import com.alibaba.fastjson.JSONObject;
import com.ly.subway.coupon.center.model.base.CommonResult;
import com.ly.subway.coupon.center.model.dto.coupon.CouponInfoResponseDTO;
import com.ly.subway.coupon.center.model.dto.coupon.SendCouponRequestDTO;
import com.ly.subway.coupon.center.ui.faceda.CouponApi;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** @author guanchao.xu* @title: GoodsPromotionApplicationTest* @description: 商品推广测试用例* @date 2022-3-1 14:55*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = CouponCenterApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class CouponApplicationTest {@Autowiredprivate Demo demo;@AutowiredCouponApi couponApi;@Testpublic void test1() {List apiList = demo.getApiList();for (ApiObj apiObj : apiList) {String keyUrl = apiObj.getUrl();String reqParam = apiObj.getReqParam();String execResult = apiObj.getResult();try {String result = HttpClientUtils.post(keyUrl, reqParam);System.out.println("result" + result);System.out.println("execResult" + execResult);System.out.println(keyUrl+"是否相等"+execResult.equals(result));} catch (IOException e) {e.printStackTrace();}}}
}

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
【PdgCntEditor】解... 一、问题背景 大部分的图书对应的PDF,目录中的页码并非PDF中直接索引的页码...
修复 爱普生 EPSON L4... L4151 L4153 L4156 L4158 L4163 L4165 L4166 L4168 L4...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...