TestNG+HttpClient+Excel數據驅動測試

數據驅動測試

數據驅動測試的核心是:測試數據與測試腳本分離,實現測試腳本參數化牍蜂,提高測試腳本的可重用性钳降。在自動化功能測試中如果靈活使用數據源與測試腳本厚宰,便能輕松創(chuàng)建與運行成百上千個測試用例。自動化測試框架必須要有與電子表格遂填、文本文件铲觉、數據庫集成的能力。

TestNG

TestNG是受JUnit和NUnit測試框架的啟發(fā)而設計的吓坚,但引其中入一些新的功能撵幽,使它更強大和更容易使用。(JUnit和NUnit我沒用過礁击,不做評價)

Apache POI

Apache POI項目的使命是開發(fā)和維護各種基于Office Open XML 標準(OOXML)和微軟文檔格式的Java api并齐,使用Apache POI,可以方便讀寫微軟EXCEL客税、word况褪、ppt等文檔。

怎么做:

第一步:工具準備
第一步:創(chuàng)建一個登錄接口測試用例

第二步:用Excel創(chuàng)建測試數據

第三步:使用Apache POI打開與讀取Excel數據

第四步:創(chuàng)建TestNg測試用例并使用Data Provider從Excel讀取數據

第五步:根據測試用例名稱運行測試

第一步:工具準備

1.OS:win10 家庭中文版
2.JDK:jdk-8u66-windows-x64.exe
3.Eclipse:eclipse-inst-win64.exe
4.TestNG插件
5.HttpClient:httpcomponents-client-4.5.2-bin.zip
6.Apache POI:poi-bin-3.14.zip

第一步:創(chuàng)建一個查詢接口測試用例

1.創(chuàng)建一個TestNG類:DataProviderTest

2.引用注釋Dataprovider,這個方法會返回對象數組

3.準備兩條數據更耻,一條url测垛,一條POST的json參數

4.在@Test下寫一個查詢測試用例

package testData;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
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.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class DataProviderTest {
  @DataProvider(name="Authentication")
  public static Object[][] credentials(){
     String p1="http://192.168.1.55:8182/ebe/api/query_server/v1/query";
     String pd="{'sqlText':'select * from ts','pageSize':'100','pageNum':'1'}";
     return new Object[][] {{p1,pd}};
  }
  @Test(dataProvider="Authentication")
  public void QuickStart(String p1,String pd) throws Exception {
      CloseableHttpClient httpclient = HttpClients.createDefault();
      try {
         HttpPost httpPost = new HttpPost(p1);
          JSONObject jsonParam=new JSONObject(pd);
          StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8"); 
          entity.setContentEncoding("UTF-8");
          entity.setContentType("application/json");    
          httpPost.setEntity(entity);
         CloseableHttpResponse response2 = httpclient.execute(httpPost);
         try {
              System.out.println(response2.getStatusLine());
              HttpEntity entity2 = response2.getEntity();
              System.out.println("Response content: " + EntityUtils.toString(entity2));
              // do something useful with the response body
              // and ensure it is fully consumed
              EntityUtils.consume(entity2);
          } finally {
              response2.close();
          }
      } finally {
          httpclient.close();
      }
  }

}

第三步:用Excel創(chuàng)建測試數據

1.在該項目下新建一個testdata.xlxs文件,并寫入內容

測試數據.png

第四步:使用Apache POI打開與讀取Excel數據

1.我們需要從Excel中讀取測試數據秧均,所以這里就是用Apache POI對Excel進行操作食侮。


package testData;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 
public class ExcelUtils {
    private static XSSFSheet ExcelWSheet;
    private static XSSFWorkbook ExcelWBook;
    private static XSSFCell Cell;
    private static XSSFRow Row;
    public static Object[][] getTableArray(String FilePath, String SheetName) throws Exception {   
       String[][] tabArray = null;
       try {
           FileInputStream ExcelFile = new FileInputStream(FilePath);
           // Access the required test data sheet
           ExcelWBook = new XSSFWorkbook(ExcelFile);
           ExcelWSheet = ExcelWBook.getSheet(SheetName);
           int startRow = 1;
           int startCol = 1;
           int ci,cj;
           int totalRows = ExcelWSheet.getLastRowNum();
           System.out.println(totalRows);
           // you can write a function as well to get Column count
           int totalCols = 2;
           System.out.println(totalCols);
           tabArray=new String[totalRows][totalCols];
           ci=0;
           for (int i=startRow;i<=totalRows;i++, ci++) {               
              cj=0;
               for (int j=startCol;j<=totalCols;j++, cj++){
                   tabArray[ci][cj]=getCellData(i,j);
                   System.out.println(tabArray[ci][cj]);  
                    }
                }
            }
        catch (FileNotFoundException e){
            System.out.println("Could not read the Excel sheet");
            e.printStackTrace();
            }
        catch (IOException e){
            System.out.println("Could not read the Excel sheet");
            e.printStackTrace();
            }
        return(tabArray);
        }
    public static String getCellData(int RowNum, int ColNum) throws Exception {
        try{
            Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
            int dataType = Cell.getCellType();
            if  (dataType == 3) {
                return "";
            }
            else{
                String CellData = Cell.getStringCellValue();
                return CellData;
            }
        }
            catch (Exception e){
            System.out.println(e.getMessage());
            throw (e);
            }
        }
    }
   
            
 
    
        
        
        

第五步:創(chuàng)建TestNg測試用例并使用Data Provider從Excel讀取數據

1.創(chuàng)建TestNG類:DataProviderWithExcel,從excel中導入數據,并執(zhí)行query操作

package testData;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class DataProviderWithExcel {
 @DataProvider
  public Object[][] Authentication() throws Exception{
      Object[][] testObjArray=ExcelUtils.getTableArray("F://Users//Tangxi//workspace//apiTest//src//testData//testData.xlsx", "Sheet1");
      return (testObjArray);
 }
  @Test(dataProvider="Authentication")
  public void QuickStart(String p1,String pd) throws Exception {
      CloseableHttpClient httpclient = HttpClients.createDefault();
      try {
         HttpPost httpPost = new HttpPost(p1);
          JSONObject jsonParam=new JSONObject(pd);
          StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8"); 
          entity.setContentEncoding("UTF-8");
          entity.setContentType("application/json");    
          httpPost.setEntity(entity);
         CloseableHttpResponse response2 = httpclient.execute(httpPost);
         try {
              System.out.println(response2.getStatusLine());
              HttpEntity entity2 = response2.getEntity();
              System.out.println("Response content: " + EntityUtils.toString(entity2));
              // do something useful with the response body
              // and ensure it is fully consumed
              EntityUtils.consume(entity2);
          } finally {
              response2.close();
          }
      } finally {
          httpclient.close();
      }
  }

}

第六步:根據測試用例名稱運行測試

package testData;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtils2 {
   private static XSSFSheet ExcelWSheet;
   private static XSSFWorkbook ExcelWBook;
   private static XSSFCell Cell;
   private static XSSFRow Row;


//This method is to set the File path and to open the Excel file, Pass Excel Path and Sheetname as Arguments to this method

    public static void setExcelFile(String Path,String SheetName) throws Exception {
          try {
               // Open the Excel file
               FileInputStream ExcelFile = new FileInputStream(Path);
               // Access the required test data sheet
               ExcelWBook = new XSSFWorkbook(ExcelFile);
               ExcelWSheet = ExcelWBook.getSheet(SheetName);
               } catch (Exception e){
                   throw (e);
               }
       }

    public static Object[][] getTableArray(String FilePath, String SheetName, int iTestCaseRow)    throws Exception
    
    {   
      String[][] tabArray = null;
      try{
          FileInputStream ExcelFile = new FileInputStream(FilePath);
          // Access the required test data sheet
          ExcelWBook = new XSSFWorkbook(ExcelFile);
          ExcelWSheet = ExcelWBook.getSheet(SheetName);
          int startCol = 1;
          int ci=0,cj=0;
          int totalRows = 1;
          int totalCols = 2;
          tabArray=new String[totalRows][totalCols];
              for (int j=startCol;j<=totalCols;j++, cj++)
              {
                  tabArray[ci][cj]=getCellData(iTestCaseRow,j);
                  System.out.println(tabArray[ci][cj]);
              }
       }
       catch (FileNotFoundException e)
       {
           System.out.println("Could not read the Excel sheet");
           e.printStackTrace();
       }
       catch (IOException e)
       {
           System.out.println("Could not read the Excel sheet");
           e.printStackTrace();
       }
       return(tabArray);
    
    }
    
    //This method is to read the test data from the Excel cell, in this we are passing parameters as Row num and Col num
    
    public static String getCellData(int RowNum, int ColNum) throws Exception{
      try{
         Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
         String CellData = Cell.getStringCellValue();
         return CellData;
         }catch (Exception e){
           return"";
           }
       }
    
    public static String getTestCaseName(String sTestCase)throws Exception{
       String value = sTestCase;
       try{
           int posi = value.indexOf("@");
           value = value.substring(0, posi);
           posi = value.lastIndexOf(".");    
           value = value.substring(posi + 1);
            System.out.println(value);
           return value;
               }catch (Exception e){
           throw (e);
                   }
       }
    
    public static int getRowContains(String sTestCaseName, int colNum) throws Exception{
       int i;
       try {
           int rowCount = ExcelUtils2.getRowUsed();
           for ( i=0 ; i<rowCount; i++){
               if  (ExcelUtils2.getCellData(i,colNum).equalsIgnoreCase(sTestCaseName)){
                   break;
               }
           }
           return i;
               }catch (Exception e){
           throw(e);
           }
       }
    
    public static int getRowUsed() throws Exception {
           try{
               int RowCount = ExcelWSheet.getLastRowNum();
               return RowCount;
           }catch (Exception e){
               System.out.println(e.getMessage());
               throw (e);
           }
       }
    }

最后的測試用例

1.獲取測試用例名稱
2.根據測試用例名稱獲取對應的行號
3.從對應的行中獲取測試數據

package testData;

import java.util.concurrent.TimeUnit;

import org.testng.annotations.Test;
 
import org.testng.annotations.BeforeMethod;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.testng.annotations.AfterMethod;
 
import org.testng.annotations.DataProvider;
 
import testData.ExcelUtils2;
 
public class DataProviderWithExcel_002 {
     
        private String sTestCaseName;
     
        private int iTestCaseRow;
     @Test(dataProvider = "Authentication")
     public void QuickStart(String p1,String pd) throws Exception {
          CloseableHttpClient httpclient = HttpClients.createDefault();
          try {
             HttpPost httpPost = new HttpPost(p1);
              JSONObject jsonParam=new JSONObject(pd);
              StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8"); 
              entity.setContentEncoding("UTF-8");
              entity.setContentType("application/json");    
              httpPost.setEntity(entity);
             CloseableHttpResponse response2 = httpclient.execute(httpPost);
             try {
                  System.out.println(response2.getStatusLine());
                  HttpEntity entity2 = response2.getEntity();
                  System.out.println("Response content: " + EntityUtils.toString(entity2));
                  // do something useful with the response body
                  // and ensure it is fully consumed
                  EntityUtils.consume(entity2);
              } finally {
                  response2.close();
              }
          } finally {
              httpclient.close();
          }
      }
     @DataProvider
     public Object[][] Authentication() throws Exception{
     
            // Setting up the Test Data Excel file
     
            ExcelUtils2.setExcelFile("F://Users//Tangxi//workspace//apiTest//src//testData//testData.xlsx","Sheet1");
     
            sTestCaseName = this.toString();
     
            // From above method we get long test case name including package and class name etc.
     
            // The below method will refine your test case name, exactly the name use have used
     
            sTestCaseName = ExcelUtils2.getTestCaseName(this.toString());
            System.out.println(sTestCaseName);
     
            // Fetching the Test Case row number from the Test Data Sheet
     
            // Getting the Test Case name to get the TestCase row from the Test Data Excel sheet
     
            iTestCaseRow = ExcelUtils2.getRowContains(sTestCaseName,0);
            System.out.println(iTestCaseRow);
     
            Object[][] testObjArray = ExcelUtils2.getTableArray("F://Users//Tangxi//workspace//apiTest//src//testData//testData.xlsx","Sheet1",iTestCaseRow);
     
                return (testObjArray);
     
            }
     
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末目胡,一起剝皮案震驚了整個濱河市锯七,隨后出現的幾起案子,更是在濱河造成了極大的恐慌誉己,老刑警劉巖眉尸,帶你破解...
    沈念sama閱讀 206,214評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡噪猾,警方通過查閱死者的電腦和手機霉祸,發(fā)現死者居然都...
    沈念sama閱讀 88,307評論 2 382
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來袱蜡,“玉大人丝蹭,你說我怎么就攤上這事∑阂希” “怎么了奔穿?”我有些...
    開封第一講書人閱讀 152,543評論 0 341
  • 文/不壞的土叔 我叫張陵,是天一觀的道長敏晤。 經常有香客問我巫橄,道長,這世上最難降的妖魔是什么茵典? 我笑而不...
    開封第一講書人閱讀 55,221評論 1 279
  • 正文 為了忘掉前任湘换,我火速辦了婚禮,結果婚禮上统阿,老公的妹妹穿的比我還像新娘彩倚。我一直安慰自己,他們只是感情好扶平,可當我...
    茶點故事閱讀 64,224評論 5 371
  • 文/花漫 我一把揭開白布帆离。 她就那樣靜靜地躺著,像睡著了一般结澄。 火紅的嫁衣襯著肌膚如雪哥谷。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,007評論 1 284
  • 那天麻献,我揣著相機與錄音们妥,去河邊找鬼。 笑死勉吻,一個胖子當著我的面吹牛监婶,可吹牛的內容都是我干的。 我是一名探鬼主播齿桃,決...
    沈念sama閱讀 38,313評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼惑惶,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了短纵?” 一聲冷哼從身側響起带污,我...
    開封第一講書人閱讀 36,956評論 0 259
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎香到,沒想到半個月后鱼冀,有當地人在樹林里發(fā)現了一具尸體报破,經...
    沈念sama閱讀 43,441評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 35,925評論 2 323
  • 正文 我和宋清朗相戀三年雷绢,在試婚紗的時候發(fā)現自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片理卑。...
    茶點故事閱讀 38,018評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡翘紊,死狀恐怖,靈堂內的尸體忽然破棺而出藐唠,到底是詐尸還是另有隱情帆疟,我是刑警寧澤,帶...
    沈念sama閱讀 33,685評論 4 322
  • 正文 年R本政府宣布宇立,位于F島的核電站踪宠,受9級特大地震影響,放射性物質發(fā)生泄漏妈嘹。R本人自食惡果不足惜柳琢,卻給世界環(huán)境...
    茶點故事閱讀 39,234評論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望润脸。 院中可真熱鬧柬脸,春花似錦、人聲如沸毙驯。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,240評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽爆价。三九已至垦巴,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間铭段,已是汗流浹背骤宣。 一陣腳步聲響...
    開封第一講書人閱讀 31,464評論 1 261
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留序愚,地道東北人涯雅。 一個月前我還...
    沈念sama閱讀 45,467評論 2 352
  • 正文 我出身青樓,卻偏偏與公主長得像展运,于是被迫代替她去往敵國和親活逆。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 42,762評論 2 345

推薦閱讀更多精彩內容