51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

手机号码,快捷登录

查看: 2357|回复: 1
打印 上一主题 下一主题

[讨论] TestNG+HttpClient+Excel数据驱动测试

[复制链接]
  • TA的每日心情
    无聊
    4 小时前
  • 签到天数: 58 天

    连续签到: 1 天

    [LV.5]测试团长

    跳转到指定楼层
    1#
    发表于 2018-5-30 16:48:04 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
    数据驱动测试

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

    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下写一个查询测试用例

    1. <p>package testData;</p><p>
    2. </p><p>import java.io.IOException;</p><p>
    3. </p><p>import org.apache.http.HttpEntity;</p><p>import org.apache.http.client.ClientProtocolException;</p><p>import org.apache.http.client.methods.CloseableHttpResponse;</p><p>import org.apache.http.client.methods.HttpGet;</p><p>import org.apache.http.client.methods.HttpPost;</p><p>import org.apache.http.entity.StringEntity;</p><p>import org.apache.http.impl.client.CloseableHttpClient;</p><p>import org.apache.http.impl.client.HttpClients;</p><p>import org.apache.http.util.EntityUtils;</p><p>import org.json.JSONException;</p><p>import org.json.JSONObject;</p><p>import org.testng.annotations.DataProvider;</p><p>import org.testng.annotations.Test;</p><p>
    4. </p><p>public class DataProviderTest {</p><p>  @DataProvider(name="Authentication")</p><p>  public static Object[][] credentials(){</p><p>     String p1="http://192.168.1.55:8182/ebe/api/query_server/v1/query";</p><p>     String pd="{'sqlText':'select * from ts','pageSize':'100','pageNum':'1'}";</p><p>     return new Object[][] {{p1,pd}};</p><p>  }</p><p>  @Test(dataProvider="Authentication")</p><p>  public void QuickStart(String p1,String pd) throws Exception {</p><p>      CloseableHttpClient httpclient = HttpClients.createDefault();</p><p>      try {</p><p>         HttpPost httpPost = new HttpPost(p1);</p><p>          JSONObject jsonParam=new JSONObject(pd);</p><p>          StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8"); </p><p>          entity.setContentEncoding("UTF-8");</p><p>          entity.setContentType("application/json");    </p><p>          httpPost.setEntity(entity);</p><p>         CloseableHttpResponse response2 = httpclient.execute(httpPost);</p><p>         try {</p><p>              System.out.println(response2.getStatusLine());</p><p>              HttpEntity entity2 = response2.getEntity();</p><p>              System.out.println("Response content: " + EntityUtils.toString(entity2));</p><p>              // do something useful with the response body</p><p>              // and ensure it is fully consumed</p><p>              EntityUtils.consume(entity2);</p><p>          } finally {</p><p>              response2.close();</p><p>          }</p><p>      } finally {</p><p>          httpclient.close();</p><p>      }</p><p>  }</p><p>
    5. </p><p>}</p>
    复制代码

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

    1.在该项目下新建一个testdata.xlxs文件,并写入内容

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

    1.我们需要从Excel中读取测试数据,所以这里就是用Apache POI对Excel进行操作。

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








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

    1.创建TestNG类:DataProviderWithExcel,从excel中导入数据,并执行query操作
    1. <p>
    2. </p><p>package testData;</p><p>
    3. </p><p>import org.apache.http.HttpEntity;</p><p>import org.apache.http.client.methods.CloseableHttpResponse;</p><p>import org.apache.http.client.methods.HttpPost;</p><p>import org.apache.http.entity.StringEntity;</p><p>import org.apache.http.impl.client.CloseableHttpClient;</p><p>import org.apache.http.impl.client.HttpClients;</p><p>import org.apache.http.util.EntityUtils;</p><p>import org.json.JSONObject;</p><p>import org.testng.annotations.DataProvider;</p><p>import org.testng.annotations.Test;</p><p>
    4. </p><p>public class DataProviderWithExcel {</p><p> @DataProvider</p><p>  public Object[][] Authentication() throws Exception{</p><p>      Object[][] testObjArray=ExcelUtils.getTableArray("F://Users//Tangxi//workspace//apiTest//src//testData//testData.xlsx", "Sheet1");</p><p>      return (testObjArray);</p><p> }</p><p>
    5. </p>
    复制代码




    本帖子中包含更多资源

    您需要 登录 才可以下载或查看,没有帐号?(注-册)加入51Testing

    x
    分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

  • TA的每日心情
    无聊
    4 小时前
  • 签到天数: 58 天

    连续签到: 1 天

    [LV.5]测试团长

    2#
     楼主| 发表于 2018-5-30 16:48:44 | 只看该作者
      @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);
         
                }
         
        }
    回复 支持 反对

    使用道具 举报

    本版积分规则

    关闭

    站长推荐上一条 /1 下一条

    小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

    GMT+8, 2024-9-20 14:59 , Processed in 0.061789 second(s), 23 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

    快速回复 返回顶部 返回列表