最近研究了下java實現接口自動化,借助testng+excel實現數據驅動,記錄下
代碼記錄下:
pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.ygsoft.test</groupId> <artifactId>api</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>api</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.0.1</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.0.1</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.6</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5.6</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.10</version> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.14.3</version> <scope>test</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.52</version> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> </project>
Paras.properties

base_url=http://10.121.55.41:8080 #Realinsight #login_url=http://10.121.55.41:8080/api/v1/login/default #login_request={"username":"04ba024b471d006ca514a00fbaa70c3b74cac10d79a1d0c20ffedee6d8a32778fa5c40bfc0c8e14cdb12cca64af62e2396b15d4f1e466f5319e456304fa4d652f5ea2d238b299d6ae6cfed3dbb2e7c67de081cc036d4d67a21164ebc49b6921e0acf97da44dadea9e6","password":"04ba024b471d006ca514a00fbaa70c3b74cac10d79a1d0c20ffedee6d8a32778fa5c40bfc0c8e14cdb12cca64af62e2396b15d4f1e466f5319e456304fa4d652f5a27864da748838b4d83033116215a667e802d78ce0e0097af337e89322c1ad81f5efee7a471f6ad701","code":""} #ETL login_url=http://10.121.55.41/api/v1/login/default login_request={"username":"04281739551a4a21b497fccc38a59d15a4923427f176aa34545dfae05dad2bb89033783740f7a37a1019e225312c3ea20772cbe08e43ff47db2b6e191714724aea2d71d47cb86fefccdbfed490c51512e8f32b503399d6a41b16afec106686ac52c8308b8e29474f","password":"04ba024b471d006ca514a00fbaa70c3b74cac10d79a1d0c20ffedee6d8a32778fa5c40bfc0c8e14cdb12cca64af62e2396b15d4f1e466f5319e456304fa4d652f5a27864da748838b4d83033116215a667e802d78ce0e0097af337e89322c1ad81f5efee7a471f6ad701","code":""} login_admin={"username":"04281739551a4a21b497fccc38a59d15a4923427f176aa34545dfae05dad2bb89033783740f7a37a1019e225312c3ea20772cbe08e43ff47db2b6e191714724aea2160c9c119431541e1673498b9740918d43042c3ba161a304ba2d079d300f5afc181ee","password":"04281739551a4a21b497fccc38a59d15a4923427f176aa34545dfae05dad2bb89033783740f7a37a1019e225312c3ea20772cbe08e43ff47db2b6e191714724aea7d338e3cf37df9abc1cb807b6f672ebfcf827c2697a91a674ac62d546b42e07ae9fe591bfb16df7667","code":""} logout_url=http://10.121.55.41:8080/api/v1/logout RealinsightAPI=Realinsight etlAPI=ETL
ExcelUtil.Java

package com.ygsoft.test.api; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.NumberFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.FormulaEvaluator; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * 只支持讀取 .xlsx 所有方法讀取數據時 * * @version 1.0 */ public class ExcelUtil{ static FormulaEvaluator formulaEvaluator = null; static XSSFWorkbook wb; public static List<Map<String, String>> getTestData(String fileName, String sheetName) throws Exception { File file = new File(fileName); FileInputStream inputStream = new FileInputStream(file); wb = new XSSFWorkbook(inputStream); formulaEvaluator = new XSSFFormulaEvaluator((XSSFWorkbook) wb); XSSFSheet s = wb.getSheet(sheetName); Map<String, String> map = null; List<Map<String, String>> list = new ArrayList<Map<String, String>>(); // 獲取第一行作為key XSSFRow title = s.getRow(0); List<String> keys = new ArrayList<String>(); for (int i = 0; i < title.getLastCellNum(); i++) { Cell cell = title.getCell(i); keys.add(getValue(cell)); } for (int row = 1; row <= s.getLastRowNum(); row++) { map = new HashMap<String, String>(); XSSFRow r = s.getRow(row); if (r == null) { continue; } // 遍歷單元格 cell for (int cell = 0; cell <= r.getLastCellNum(); cell++) { XSSFCell c = r.getCell(cell); if (c == null) { continue; } map.put(keys.get(cell), getValue(c)); } list.add(map); } if (inputStream != null) { inputStream.close(); } if (wb != null) { wb.close(); } return list; } public static String getValue(Cell cell) { if (cell.getCellType() == CellType.BOOLEAN) { return String.valueOf(cell.getBooleanCellValue()); } else if (cell.getCellType() == CellType.NUMERIC) { NumberFormat numberFormat = NumberFormat.getInstance(); numberFormat.setGroupingUsed(false); return numberFormat.format(cell.getNumericCellValue()); } else if (cell.getCellType() == CellType.FORMULA) { wb.getCreationHelper().createFormulaEvaluator().evaluateFormulaCell(cell); String strCell; try { strCell = String.valueOf(cell.getNumericCellValue()); } catch (IllegalStateException e) { strCell = cell.getStringCellValue(); } return strCell; } else { return cell.getStringCellValue(); } } public static void writeData(String fileName, String sheetName, int row, int column, String content, String color) throws Exception { File file = new File(fileName); FileInputStream inputStream = new FileInputStream(file); XSSFWorkbook wb = new XSSFWorkbook(inputStream); XSSFSheet s = wb.getSheet(sheetName); // 如果單元格是空就創建新單元格在修改 if (s.getRow(row) == null) { s.createRow(row); } if (s.getRow(row).getCell(column) == null) { s.getRow(row).createCell(column); } // 填充內容 Cell cell = s.getRow(row).getCell(column); cell.setCellValue(content); CellStyle cellStyle = wb.createCellStyle(); // 填充單元格 if (color == null) { } else if (color.contains("RED")) { cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex()); cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); } else if (color.contains("GREEN")) { cellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex()); cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); } else if (color.contains("YELLOW")) { cellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); } cell.setCellStyle(cellStyle); FileOutputStream outputStream = new FileOutputStream(fileName); wb.setForceFormulaRecalculation(true); XSSFFormulaEvaluator.evaluateAllFormulaCells(wb); wb.write(outputStream); outputStream.flush(); outputStream.close(); if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } if (wb != null) { wb.close(); } } public static int getRowNum(String fileName, String sheetName) throws Exception { File file = new File(fileName); FileInputStream inputStream = new FileInputStream(file); wb = new XSSFWorkbook(inputStream); formulaEvaluator = new XSSFFormulaEvaluator((XSSFWorkbook) wb); XSSFSheet s = wb.getSheet(sheetName); int rowNum=s.getLastRowNum(); if (inputStream != null) { inputStream.close(); } if (wb != null) { wb.close(); } return rowNum; } public static int getColumnNum(String fileName, String sheetName,String columnString) throws Exception{ int column = 0; FileInputStream inputStream = new FileInputStream(new File(fileName)); wb = new XSSFWorkbook(inputStream); XSSFSheet s = wb.getSheet(sheetName); // 獲取第一行 XSSFRow title = s.getRow(0); for (int i = 0; i < title.getLastCellNum(); i++) { Cell cell = title.getCell(i); if (getValue(cell).contains(columnString)) { column=i; } } if (inputStream != null) { inputStream.close(); } if (wb != null) { wb.close(); } return column; } }
HttpClientUtil.Java

package com.ygsoft.test.api; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import org.apache.commons.collections.map.StaticBucketMap; import org.apache.http.*; import org.apache.http.client.*; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.*; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.poi.ss.formula.functions.Column; import org.openxmlformats.schemas.wordprocessingml.x2006.main.impl.STTabTlcImpl; import org.testng.log4testng.Logger; import com.alibaba.fastjson.JSONObject; public class HttpClientUtil extends ParasUtil { final static Logger Log = Logger.getLogger(HttpClientUtil.class); public static int statusCode; public static String reponseContent; public static String Authorization; public static String token; public static HashMap<String, String> headers = new HashMap<String, String>(); /** * 不帶請求頭的get方法封裝 * * @param url * @return 返回響應對象 * @throws ClientProtocolException * @throws IOException */ public String get(String url) throws ClientProtocolException, IOException { // 創建一個可關閉的HttpClient對象 CloseableHttpClient httpclient = HttpClients.createDefault(); // 創建一個HttpGet的請求對象 HttpGet httpget = new HttpGet(url); // 執行請求,相當於postman上點擊發送按鈕,然后賦值給HttpResponse對象接收 Log.info("開始發送get請求..."); CloseableHttpResponse httpResponse = httpclient.execute(httpget); reponseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); Log.info("返回內容:" + reponseContent); return reponseContent; } /** * 帶請求頭信息的get方法 * * @param url * @param headermap,鍵值對形式 * @return 返回響應對象 * @throws ClientProtocolException * @throws IOException */ public String get(String url, HashMap<String, String> headermap) throws ClientProtocolException, IOException { // 創建一個可關閉的HttpClient對象 CloseableHttpClient httpclient = HttpClients.createDefault(); // 創建一個HttpGet的請求對象 HttpGet httpget = new HttpGet(url); // 加載請求頭到httpget對象 for (Map.Entry<String, String> entry : headermap.entrySet()) { httpget.addHeader(entry.getKey(), entry.getValue()); } // 執行請求,相當於postman上點擊發送按鈕,然后賦值給HttpResponse對象接收 CloseableHttpResponse httpResponse = httpclient.execute(httpget); reponseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); Log.info("返回內容:" + reponseContent); return reponseContent; } /** * 封裝post方法 * * @param url * @param entityString,其實就是設置請求json參數 * @param headermap,帶請求頭 * @return 返回響應對象 * @throws ClientProtocolException * @throws IOException */ public static String post(String url, String entityString, HashMap<String, String> headermap) throws ClientProtocolException, IOException { // 創建一個可關閉的HttpClient對象 CloseableHttpClient httpclient = HttpClients.createDefault(); // 創建一個HttpPost的請求對象 HttpPost httppost = new HttpPost(url); // 設置payload if (entityString != null) { httppost.setEntity(new StringEntity(entityString)); } // 加載請求頭到httppost對象 for (Map.Entry<String, String> entry : headermap.entrySet()) { httppost.addHeader(entry.getKey(), entry.getValue()); } // 發送post請求 CloseableHttpResponse httpResponse = httpclient.execute(httppost); statusCode = httpResponse.getStatusLine().getStatusCode(); Log.info("返回狀態碼:" + statusCode); reponseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); Log.info("返回內容:" + reponseContent); return reponseContent; } /** * 封裝 put請求方法,參數和post方法一樣 * * @param url * @param entityString,這個主要是設置payload,一般來說就是json串 * @param headerMap,帶請求的頭信息,格式是鍵值對,所以這里使用hashmap * @return 返回響應對象 * @throws ClientProtocolException * @throws IOException */ public CloseableHttpResponse put(String url, String entityString, HashMap<String, String> headerMap) throws ClientProtocolException, IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPut httpput = new HttpPut(url); httpput.setEntity(new StringEntity(entityString)); for (Map.Entry<String, String> entry : headerMap.entrySet()) { httpput.addHeader(entry.getKey(), entry.getValue()); } // 發送put請求 CloseableHttpResponse httpResponse = httpclient.execute(httpput); return httpResponse; } /** * 封裝 delete請求方法,參數和get方法一樣 * * @param url, * 接口url完整地址 * @return,返回一個response對象,方便進行得到狀態碼和json解析動作 * @throws ClientProtocolException * @throws IOException */ public CloseableHttpResponse delete(String url) throws ClientProtocolException, IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpDelete httpdel = new HttpDelete(url); // 發送delete請求 CloseableHttpResponse httpResponse = httpclient.execute(httpdel); return httpResponse; } public static String UploadFile(String url, File file, HashMap<String, String> headermap) { CloseableHttpClient httpClient = HttpClients.createDefault(); // 每個post參數之間的分隔。隨意設定,只要不會和其他的字符串重復即可。 String boundary = "----WebKitFormBoundarya4boZUDstbGAOHbb"; try { String fileName = file.getName(); HttpPost httpPost = new HttpPost(url); // 加載請求頭到httppost對象 for (Map.Entry<String, String> entry : headermap.entrySet()) { httpPost.addHeader(entry.getKey(), entry.getValue()); } httpPost.addHeader("Content-Type", "multipart/form-data; boundary=" + boundary); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, fileName); builder.setCharset(Charset.forName("UTF-8")); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.setBoundary(boundary); builder.addPart("multipartFile", new FileBody(file)); builder.addTextBody("filename", fileName, ContentType.create("text/plain", Consts.UTF_8)); HttpEntity entity = builder.build(); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost); reponseContent = EntityUtils.toString(response.getEntity(), "UTF-8"); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println("reponseContent:" + reponseContent); return reponseContent; } public static void login() { headers.put("Content-Type", "application/json;charset=UTF-8"); try { String response = post(login_url, login_request, headers); JSONObject jsonObject = JSONObject.parseObject(response); token = jsonObject.getString("access_token"); Authorization = "bearer " + jsonObject.getString("access_token"); System.out.println("登陸成功\nAuthorization:" + Authorization); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void login_admin() { headers.put("Content-Type", "application/json;charset=UTF-8"); try { String response = post(login_url, login_admin, headers); JSONObject jsonObject = JSONObject.parseObject(response); token = jsonObject.getString("access_token"); Authorization = "bearer " + jsonObject.getString("access_token"); System.out.println("登陸成功\nAuthorization:" + Authorization); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void logout() { headers.put("Content-Type", "application/x-www-form-urlencoded"); headers.put("Authorization", Authorization); try { post(logout_url, null, headers); System.out.println("退出登陸成功"); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // 返回報文寫入excel並格式化單元格 public static void writeResult(String fileName, String sheetName, int row, int statusCodeColumn, int reponseContentColumn, int resultColumn,int responseKeyColumn, String excepedReponse,String responseKey) { try { ExcelUtil.writeData(fileName, sheetName, row, statusCodeColumn, String.valueOf(statusCode), null); ExcelUtil.writeData(fileName, sheetName, row, reponseContentColumn, reponseContent, null); // 如果返回包含預期輸入 if (reponseContent.contains(excepedReponse)) { ExcelUtil.writeData(fileName, sheetName, row, resultColumn, "pass", "GREEN"); } else { ExcelUtil.writeData(fileName, sheetName, row, resultColumn, "failed", "RED"); } if (responseKey!=null) { String value=JsonUtil.getKeyValue(reponseContent, responseKey); ExcelUtil.writeData(fileName, sheetName, row, responseKeyColumn, value,null); } } catch (Exception e) { e.printStackTrace(); } } }
ParasUtil.Java

package com.ygsoft.test.api; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.openxmlformats.schemas.wordprocessingml.x2006.main.impl.STTabTlcImpl; public class ParasUtil { static String fileName; static String base_url; static String login_url; static String login_request; static String login_admin; static String logout_url; static String RealinsightAPI; static String etlAPI; public static void readParas(){ try { ParasUtil.fileName=System.getProperty("user.dir")+"\\datas\\test.xlsx"; System.out.println("接口文檔路徑 \n"+ParasUtil.fileName); InputStream inStream = new FileInputStream(new File(System.getProperty("user.dir")+"\\datas\\Paras.properties")); Properties prop = new Properties(); prop.load(inStream); ParasUtil.base_url=prop.getProperty("base_url"); ParasUtil.login_url=prop.getProperty("login_url"); ParasUtil.login_request=prop.getProperty("login_request"); ParasUtil.login_admin=prop.getProperty("login_admin"); ParasUtil.logout_url=prop.getProperty("logout_url"); ParasUtil.RealinsightAPI=prop.getProperty("RealinsightAPI"); ParasUtil.etlAPI=prop.getProperty("etlAPI"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
JsonUtil.Java

package com.ygsoft.test.api; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class JsonUtil { static List<String> keyValue=new ArrayList<>(); // java遞歸遍歷json對象,支持無限層級 public static void analysisJson(Object objJson) { // 如果obj為json數組 if (objJson instanceof JSONArray) { JSONArray objArray = (JSONArray) objJson; for (int i = 0; i < objArray.size(); i++) { analysisJson(objArray.get(i)); } } // 如果為json對象 else if (objJson instanceof JSONObject) { JSONObject jsonObject = (JSONObject) objJson; Iterator it = jsonObject.keys(); while (it.hasNext()) { String key = it.next().toString(); Object object = jsonObject.get(key); // 如果得到的是數組 if (object instanceof JSONArray) { JSONArray objArray = (JSONArray) object; analysisJson(objArray); } // 如果key中是一個json對象 else if (object instanceof JSONObject) { analysisJson((JSONObject) object); } // 如果key中是其他 else { System.out.println("[" + key + "]:" + object.toString() + " "); } } } } // java遞歸遍歷json對象,查看鍵值 public static String getKeyValue(Object objJson, String test) { // 如果obj為json數組 if (objJson instanceof JSONArray) { JSONArray objArray = (JSONArray) objJson; for (int i = 0; i < objArray.size(); i++) { getKeyValue(objArray.get(i), test); } } // 如果為json對象 else if (objJson instanceof JSONObject) { JSONObject jsonObject = (JSONObject) objJson; Iterator it = jsonObject.keys(); while (it.hasNext()) { String key = it.next().toString(); Object object = jsonObject.get(key); // 如果得到的是數組 if (object instanceof JSONArray) { JSONArray objArray = (JSONArray) object; getKeyValue(objArray, test); } // 如果key中是一個json對象 else if (object instanceof JSONObject) { getKeyValue((JSONObject) object, test); } // 如果key中是其他 else { // System.out.println("[" + key + "]:" + object.toString() + " "); if (key.contains(test)) { keyValue.add(object.toString()); break; } } } } return keyValue.get(0); } public static String getKeyValue(String jsonStr, String test) { if (jsonStr.startsWith("{")) { JSONObject objJson = JSONObject.fromObject(jsonStr); return JsonUtil.getKeyValue(objJson, test); }else if(jsonStr.startsWith("[")){ JSONArray jsonArray = JSONArray .fromObject(jsonStr); return JsonUtil.getKeyValue(jsonArray.toJSONObject(jsonArray), test); }else return test; } /* * 遞歸遍歷JSON對象。 * * @param JsonToMap * * @return Map */ public static Map<String, Object> IteratorHash(net.sf.json.JSONObject JsonToMap) { Iterator<?> it = JsonToMap.keys(); HashMap<String, Object> RMap = new HashMap<String, Object>(); while (it.hasNext()) { String key = String.valueOf(it.next()); if (JsonToMap.get(key).getClass() == net.sf.json.JSONArray.class) {// 判是否為列表 if (JsonToMap.getJSONArray(key).isEmpty()) {// 判列表是否為空 RMap.put(key, null); } else { List<Map<String, Object>> MapListObj = new ArrayList<Map<String, Object>>(); for (Object JsonArray : JsonToMap.getJSONArray(key)) { HashMap<String, Object> TempMap = new HashMap<String, Object>(); if (JsonArray.getClass() == String.class) { TempMap.put(key, JsonArray); } else { TempMap.putAll(IteratorHash(net.sf.json.JSONObject.fromObject(JsonArray))); } MapListObj.add(TempMap); } RMap.put(key, (Object) MapListObj); } } else if (JsonToMap.get(key).getClass() == net.sf.json.JSONObject.class) { RMap.put(key, JsonToMap.getJSONObject(key)); } else if (JsonToMap.get(key).getClass() == String.class || JsonToMap.get(key).getClass() == Integer.class || JsonToMap.get(key).getClass() == Long.class) { RMap.put(key, JsonToMap.get(key)); } } return RMap; } }
測試類
etlAPITest.Java

package com.ygsoft.test.api; import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class etlAPITest extends HttpClientUtil { @BeforeClass public void loginTest() { readParas(); login(); } @Test public void etlAPITest() throws Exception { int statusCodeColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "返回狀態碼"); int reponseContentColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "返回報文"); int resultColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "測試結果"); int responseKeyColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "返回值"); List<Map<String, String>> result; headers.put("Authorization", Authorization); for (int i = 0; i < ExcelUtil.getRowNum(fileName, etlAPI); i++) { result = ExcelUtil.getTestData(fileName, etlAPI); System.out.println(result.get(i).get("請求類型") + " " + result.get(i).get("請求頭") + " " + result.get(i).get("測試要點") + " " + result.get(i).get("輸入")); headers.put("Content-Type", result.get(i).get("請求頭")); if (result.get(i).get("請求類型").contains("POST")) { post(result.get(i).get("測試要點"), result.get(i).get("輸入"), headers); } else if (result.get(i).get("請求類型").contains("GET")) { get(result.get(i).get("測試要點"),headers); } else if (result.get(i).get("請求類型").contains("UPLOAD")) { HashMap<String, String> header = new HashMap<String, String>(); header.put("Authorization", Authorization); UploadFile(result.get(i).get("測試要點"), new File(result.get(i).get("輸入")), header); } writeResult(fileName, etlAPI, Integer.parseInt(result.get(i).get("序號")), statusCodeColumn, reponseContentColumn, resultColumn, responseKeyColumn, result.get(i).get("預期輸出"), result.get(i).get("返回鍵")); } } @AfterClass public void logoutTest() { logout(); } }
RealinsightAPITest.Java

package com.ygsoft.test.api; import java.util.List; import java.util.Map; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class RealinsightAPITest extends HttpClientUtil { @BeforeClass public void loginTest() { readParas(); login_admin(); } @Test public void RealinsightAPITest() throws Exception { int statusCodeColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "返回狀態碼"); int reponseContentColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "返回報文"); int resultColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "測試結果"); int responseKeyColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "返回值"); List<Map<String, String>> result; headers.put("Authorization", Authorization); for (int i = 0; i < ExcelUtil.getRowNum(fileName, RealinsightAPI); i++) { result = ExcelUtil.getTestData(fileName, RealinsightAPI); System.out.println(result.get(i).get("請求類型") + " " + result.get(i).get("請求頭") + " " + result.get(i).get("測試要點") + " " + result.get(i).get("輸入")); headers.put("Content-Type", result.get(i).get("請求頭")); if (result.get(i).get("請求類型").contains("POST")) { post(result.get(i).get("測試要點"), result.get(i).get("輸入"), headers); } else if (result.get(i).get("請求類型").contains("GET")) { get(result.get(i).get("測試要點")); } writeResult(fileName, RealinsightAPI, Integer.parseInt(result.get(i).get("序號")), statusCodeColumn, reponseContentColumn, resultColumn, responseKeyColumn, result.get(i).get("預期輸出"), result.get(i).get("返回鍵")); } } @AfterClass public void logoutTest() { logout(); } /* * @DataProvider(name = "test") public Object[][] dataMethod() throws * Exception { List<Map<String, String>> result; Object[][] files = new * Object[ExcelUtil.getRowNum(fileName, Sheet1)][]; for (int i = 0; i < * ExcelUtil.getRowNum(fileName, Sheet1); i++) { * result=ExcelUtil.getTestData(fileName, Sheet1); files[i] = new Object[] { * result.get(i) }; } return files; } */ /* * @Test(dataProvider = "test") public void test(Map<String, String> param) * throws Exception { System.out.println( param.get("請求類型") + * " "+param.get("請求頭")+" " + param.get("測試要點") + " " + param.get("輸入")); * headers.put("Authorization", Authorization); headers.put("Content-Type", * param.get("請求頭")); if (param.get("請求類型").contains("POST")) { * post(param.get("測試要點"), param.get("輸入"), headers); } else if * (param.get("請求類型").contains("GET")) { get(param.get("測試要點")); } * writeResult(fileName, Sheet1, Integer.parseInt(param.get("序號")), 12, 13, * 14,16, param.get("預期輸出"),param.get("返回鍵")); } */ }
ClearResult.Java

package com.ygsoft.test.api; import java.util.List; import java.util.Map; import org.testng.annotations.Test; public class ClearResult extends HttpClientUtil { @Test public void f() throws Exception { readParas(); List<Map<String, String>> result; int statusCodeColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "返回狀態碼"); int reponseContentColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "返回報文"); int resultColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "測試結果"); int responseKeyColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "返回值"); for (int i = 0; i < ExcelUtil.getRowNum(fileName, etlAPI); i++) { result = ExcelUtil.getTestData(fileName, etlAPI); ExcelUtil.writeData(fileName, etlAPI, Integer.parseInt(result.get(i).get("序號")), statusCodeColumn, null, null); ExcelUtil.writeData(fileName, etlAPI, Integer.parseInt(result.get(i).get("序號")), reponseContentColumn, null, null); ExcelUtil.writeData(fileName, etlAPI, Integer.parseInt(result.get(i).get("序號")), resultColumn, null, null); ExcelUtil.writeData(fileName, etlAPI, Integer.parseInt(result.get(i).get("序號")), responseKeyColumn, null, null); } } }