在实际开发中测试代码时必不可少的环节,
并且通常要测试开发环境、测试环境、预发布环境、灰度测试、生产环境等
2.测试代码设计
步骤一:编写一个测试基类Base,这个基类里面主要是定义接口使用的token值、签名值的生成方法、不同环境的接口ip、测试模板等
package com.ldp.user.controller; import cn.hutool.core.util.StrUtil; import cn.hutool.crypto.SecureUtil; import cn.hutool.http.HttpRequest; import cn.hutool.http.HttpUtil; import cn.hutool.http.Method; import java.util.Map; import java.util.TreeMap; /** * @Copyright (C) 四川XXXX科技有限公司 * @Author: LI DONG PING * @Date: 2020-05-01 10:03 * @Description: <p> * http://localhost:8080/api/swagger-ui.html * </p> */ public class Base { public static String token = "eyJhbsInN1YiI6IntcImhhc1Bob25lTm9cIjp0cnVlLFwibG9naW5UeXBlXCI6MSxcInVzZXJJZFwiOjIyMX0iLCJleHAiOjE1ODc1OTI4NzJ9.2ZL06sIiTzG331K2EBy5UPWiB06PgZ8eSZAmzGlp9C-Dm39k0iI-dVNvrQBCLRhBhjevp01q3rBHWEVz3dMtWw"; /** * 用于切换测试的环境 */ public static String urlLocal = "http://localhost:8080/api"; public static String urlIp = ""; public static String urlDev = ""; public static String urlTest = ""; public static String urlPro = ""; /** * 测试模板 */ public void test() { String url = urlLocal + "/"; System.out.println("请求地址:" + url); HttpRequest request = HttpUtil.createRequest(Method.GET, url); // 注意这里使用TreeMap Map<String, Object> map = new TreeMap<>(); // 业务参数 map.put("name", "11"); // 公用参数 map.put("appid", "1001"); map.put("sequenceId", "seq" + System.currentTimeMillis()); map.put("timeStamp", System.currentTimeMillis()); map.put("sign", signApi(map, "123456")); request.form(map); System.out.println("请求参数:" + map); request.header("Authorization", token); request.setConnectionTimeout(60 * 1000); String response = request.execute().body(); System.out.println("请求结果:" + response); } /** * api接口签名规则 * * @param map * @return */ public String signApi(Map<String, Object> map, String md5Key) { StringBuilder sb = new StringBuilder(); for (String key : map.keySet()) { Object o = map.get(key); if (o == null || StrUtil.isEmpty(o.toString())) { continue; } sb.append(key + "=").append(map.get(key) + "&"); } String str1 = sb.toString(); String str = str1.substring(0, str1.length() - 1) + md5Key; String md5 = SecureUtil.md5(str); System.out.println("签名参数:" + map); System.out.println("签名key:" + md5Key); System.out.println("签名原串:" + str); System.out.println("签名签名值:" + md5); return md5; } }