TestNG+HttpClient+Excel数据驱动测试

数据驱动测试

数据驱动测试的核心是:测试数据与测试脚本分离,实现测试脚本参数化,提高测试脚本的可重用性。在自动化功能测试中如果灵活使用数据源与测试脚本,便能轻松创建与运行成百上千个测试用例。自动化测试框架必须要有与电子表格、文本文件、数据库集成的能力。

TestNG

TestNG是受JUnit和NUnit测试框架的启发而设计的,但引其中入一些新的功能,使它更强大和更容易使用。(JUnit和NUnit我没用过,不做评价)

Apache POI

Apache POI项目的使命是开发和维护各种基于Office Open XML 标准(OOXML)和微软文档格式的Java api,使用Apache POI,可以方便读写微软EXCEL、word、ppt等文档。

怎么做:

第一步:工具准备
第一步:创建一个登录接口测试用例

第二步:用Excel创建测试数据

第三步:使用Apache POI打开与读取Excel数据

第四步:创建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

第一步:创建一个查询接口测试用例

1.创建一个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创建测试数据

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);
            }
        }
    }
   
            
 
    
        
        
        

第五步:创建TestNg测试用例并使用Data Provider从Excel读取数据

1.创建TestNG类:DataProviderWithExcel,从excel中导入数据,并执行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,968评论 6 482
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,601评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 153,220评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,416评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,425评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,144评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,432评论 3 401
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,088评论 0 261
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,586评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,028评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,137评论 1 334
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,783评论 4 324
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,343评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,333评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,559评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,595评论 2 355
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,901评论 2 345

推荐阅读更多精彩内容