標籤:
此後就是資料準備與邏輯實現,就不在贅述了
此次自動化指令碼並未太多用到TestNG,僅僅用於他調試起來方便;
本章記錄一些用到的輔助方法:
1.將傳回值列印出來的get請求,用於測試或查看介面返回內容
public static void get(HashMap<String, String> params, String HOST, String PATH) { CloseableHttpClient httpclient = HttpClients.createDefault(); try { // 建立httpget請求. HttpGet httpget = new HttpGet(getUrl(getFormparams(params), HOST, PATH)); System.out.println("executing request " + httpget.getURI()); // 執行get請求 CloseableHttpResponse response = httpclient.execute(httpget); try { // 將響應放入entity載體 HttpEntity entity = response.getEntity(); System.out.println("--------------------------------------"); // 列印返回狀態列 System.out.println(response.getStatusLine()); if (entity != null) { // 列印返回內容長度 System.out.println("Response content length: " + entity.getContentLength()); // 列印返回內容 System.out.println("Response content: " + EntityUtils.toString(entity)); } System.out.println("------------------------------------"); } finally { response.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 中斷連線 try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } }
2.去掉長數組中短數組含有的元素
public static String[] unlockedSeatArray(String[] longerarray, String[] shorterarray) { LinkedList<String> list = new LinkedList<>(); for(String str : longerarray) { list.add(str); } for (String str : shorterarray) { if(list.contains(str)) { list.remove(str); } } String[] result = {}; return list.toArray(result);}
3.數組中每前n個值合并,並形成一個新的數組
public static String[] seatArray(String[] targetArray, int index) { String[] seatArray = null; int len = targetArray.length; int len2 = 0; int j = 0; //座位元迴圈變數 //計算數組的行長度 if(0==len%index){ len2 = len/index; }else{ len2 = (int)(len/index) + 1 ; } //初始化數組 seatArray = new String[len2]; len2 = 0; j = 0; for(int i=0; i<len; i++) { if(index == j) { j = 0; seatArray[len2] = seatArray[len2].substring(4, seatArray[len2].length()-1); len2++; } seatArray[len2] = seatArray[len2] + targetArray[i] + ","; j++; } seatArray[len2] = seatArray[len2].substring(4, seatArray[len2].length()-1); //處理最後一個資料 return seatArray;}
4.簡單組建記錄檔方法
public static void writefile(String response, String path) { try { SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String TimeString = time.format(new java.util.Date()); File file = new File(path); if (!file.exists()) {file.createNewFile();} FileWriter fw = new FileWriter(file, true); BufferedWriter bw = new BufferedWriter(fw); bw.append(response); bw.write("\r\n"); bw.write("---------" + "可愛的分割線" + "----------" + TimeString); bw.write("\r\n"); bw.close(); fw.close(); } catch (IOException e) { e.printStackTrace(); } }
差不多一些用到的方法記錄於此
httpclient + TestNG 介面自動化的測試 第三章