住建部歷史文化街區(qū)和歷史建筑信息平臺優(yōu)化網(wǎng)站頁面
一、前言
在java開發(fā)中經(jīng)常需要造數(shù)據(jù)進行測試接口,這里記錄一下常用的通過造數(shù)據(jù)測試接口的方法。
?
二、一般的接口傳參方式
1、接口的方式最好是使用JSON或者map的方式,這樣的好處是傳參可以靈活伸縮,返回的結果也最好是JSON或者map的方式
/*** 獲取授權訪問令牌accessToken* @param params* @return*/@PostMapping("token")JSONObject getAccessToken(@RequestBody Map<String, Object> params);
2、組裝參數(shù)方法
/*** 組裝獲取Access Token參數(shù)*/public Map<String, Object> getACTokenParam() {Map<String, Object> map = new HashMap<>();String timestamp = DateTimeUtils.getDateStr();client_secret+timestamp+client_id+username+password+grant_type+scope+client_secretString clientSecM = MD5Util.getMd5(clientSecret).toUpperCase();String passwordM = MD5Util.getMd5(password).toUpperCase();String subString = (clientSecM + timestamp + clientId + userName + passwordM + grantType + scope + clientSecM);String sign = MD5Util.getMd5(subString).toUpperCase();map.put("grant_type", grantType);map.put("client_id", clientId);map.put("timestamp", timestamp);map.put("username", userName);map.put("password", passwordM);map.put("scope", scope);map.put("sign", sign);return map;}
3.常見的造數(shù)據(jù)
隨機生成4位數(shù)
?? ?Random rand = new Random();
?? ?int randomNum = rand.nextInt(9000) + 1000;
休眠
//休眠3秒
?Thread.sleep(3000);
獲取guid
?? ?/**
?? ? * 獲取guid
?? ? *?
?? ? * @return
?? ? */
?? ?public static String getGuid() {
?? ??? ?return UUID.randomUUID().toString().replaceAll("\\-", "");
?? ?}
?
。。
/*** 獲取guid* * @return*/public static String getGuid() {return UUID.randomUUID().toString().replaceAll("\\-", "");}
三、示例
/*** 測試用戶* @throws Exception*/public void testUser() throws Exception {// 創(chuàng)建一個ObjectMapper對象ObjectMapper mapper = new ObjectMapper();// 創(chuàng)建一個Json對象ObjectNode json = mapper.createObjectNode();URL url = new URL("http://127.0.0.1/tourist-contract/register");for (int i = 0; i < 500; i++) {Random rand = new Random();int randomNum = rand.nextInt(9000) + 1000;json.put("Phone", "1308111"+randomNum);json.put("openID", "user_20000" + i);json.put("UserName", "test_" + i);json.put("unifyID", "test_" + i);json.put("userID", "test_" + i);json.put("reservedField", "reservedField");ObjectNode json1 = mapper.createObjectNode();json1.put("sender", json);json1.put("mark", "travel");log.info("注冊用戶上鏈參數(shù)json:"+json1);//休眠3秒Thread.sleep(3000);// 接口調(diào)用ltApi(json1, url, "1308111"+randomNum, "用戶注冊", "新增");}}