SeleniumWebdriver参数化详解

一、Selenium参数化介绍

这篇博客主要给大家介绍下Selenium WebDriver如何实现参数化并且应用到实际的自动化测试工作中。
简单说下参数化:

参数化的自动化测试是这样的一个框架,从某个数据文件(例如ODBC源文件、Excel文件、Csv文件、ADO对象文件等)中读取输入、输出的 测试数据,然后通过变量传入事先录制好的或手工编写的测试脚本中。其中,这些变量被用作传递(输入/输出)用来验证应用程序的测试数据。在这个过程中,数据文件的读取、测试状态和所有测试信息都被编写进测试脚本里;测试数据只包含在数据文件中,而不是脚本里,测试脚本只是一个传送数据的机制。


二、使用WebDriver实现参数化

2.1 代码实现

2.1.1 下载POI包

PS:这里就不再赘述如何搭建selenium+WebDriver的自动化环境了,大家可以参考我的其他博客。

第一步:要想用eclipse实现读写Excel的文件的功能,首先我们需要添加相关的jar包,即下图这两个jar包:




大家可以自行前往CSDN论坛下载:

Poi-3.6:http://download.csdn.net/detail/q138026310/2785428?locationNum=4&fps=1

Poi-ooxml:http://download.csdn.net/detail/whtmonkey/5803587?locationNum=6&fps=1


第二步:将下载好的jar包添加到Java Project的BuildPath中




在弹出的选项中选择”AddExternal Jars”



将刚刚下载好的两个poi包导入即可。


2.1.2 新建一个class

新建一个java Class,用来编写我们读写Excel表格数据的代码



2.1.3 编写调用数据的代码

这段代码是笔者通过对比各种方法反复尝试,编写出来确认可以正常使用的,推荐大家使用。

代码如下,不清楚的地方可以查看注释或者留言:


package seleniumdaily;

importjava.io.FileInputStream;

importjava.io.FileNotFoundException;

import java.io.IOException;

import java.text.DecimalFormat; 

importjava.util.ArrayList; 

import java.util.List; 

importorg.apache.commons.lang3.StringUtils; 

importorg.apache.poi.openxml4j.exceptions.InvalidFormatException;

importorg.apache.poi.ss.usermodel.Cell; 

importorg.apache.poi.ss.usermodel.Row; 

importorg.apache.poi.ss.usermodel.Sheet; 

importorg.apache.poi.ss.usermodel.Workbook; 

importorg.apache.poi.ss.usermodel.WorkbookFactory;

 

 

public class ExcelStandard { 

        

    public static Workbook  getWb(String path) throws InvalidFormatException,FileNotFoundException, IOException { 

 

    return WorkbookFactory.create(newFileInputStream(path));//读取Excel文件

    }

    public static SheetgetSheet(Workbook wb, int sheetIndex) { 

        if (wb == null) { 

            throw new RuntimeException("工作簿对象为空"); 

        } 

        int sheetSize =wb.getNumberOfSheets(); 

        if (sheetIndex < 0|| sheetIndex > sheetSize - 1) { 

            throw new RuntimeException("工作表获取错误"); 

        } 

        returnwb.getSheetAt(sheetIndex);  //读取sheet工作表

    } 

    public staticList<List<String>> getExcelRows( Sheet sheet,int startLine, int endLine) {  //读取Excel表的具体数据

        List<List<String>> list = newArrayList<List<String>>(); 

        // 如果开始行号和结束行号都是-1的话,则全表读取 

        if (startLine == -1) 

            startLine = 0; 

        if (endLine == -1){ 

            endLine = sheet.getLastRowNum() +1; 

        } else

            endLine += 1; 

        } 

        for (int i = startLine; i< endLine; i++) { 

            Row row = sheet.getRow(i); 

            if (row == null) { 

                System.out.println("该行为空,直接跳过"); 

                continue

            } 

            int rowSize =row.getLastCellNum(); 

            List<String> rowList = newArrayList<String>(); 

            for (int j = 0; j <rowSize; j++) {    //获取每行第一个单元格至最后一个单元格的所有内容。

                Cell cell = row.getCell(j);  //创建cell对象,获取Excel表格每行的单元格数据

                String temp = ""//创建为空的temp对象,为后续存储cell单元格的值

                if (cell == null) { 

                    System.out.println("该列为空,赋值双引号"); 

                    temp = "NULL"

                } else

                    int cellType =cell.getCellType(); 

                    switch (cellType) {  //判断单元格的数据类型,非常重要,此处不能省略

                    case Cell.CELL_TYPE_STRING

                        temp =cell.getStringCellValue().trim(); 

                        temp = StringUtils.isEmpty(temp)? "NULL" : temp;  //String类型

                        break

                    case Cell.CELL_TYPE_BOOLEAN

                        temp = String.valueOf(cell.getBooleanCellValue());  //boolean类型

                        break

                    case Cell.CELL_TYPE_FORMULA

                        temp = String.valueOf(cell.getCellFormula().trim());  //复数类型

                        break

                    case Cell.CELL_TYPE_NUMERIC

                        temp = new DecimalFormat("#.######").format(cell.getNumericCellValue());  //数字

                        break

                    case Cell.CELL_TYPE_BLANK//

                        temp = "NULL"

                        break

                    case Cell.CELL_TYPE_ERROR//错误类型

                        temp = "ERROR"

                        break

                    default

                        temp =cell.toString().trim();  //默认使用String字符串类型

                        break

                    } 

                } 

                rowList.add(temp);  //将获取到每一行的单元格数据存储到row.list

            } 

            list.add(rowList);  //将获取到的所有行、行中所有单元格数据存储到list

        } 

        return list;

    } 

    public  static List<String> getData(int column) throwsInvalidFormatException, FileNotFoundException, IOException {

    List<String>finalOutput = new ArrayList<String>(); 

        String path = "C:/Users/Administrator/Desktop/test.xls"

        Workbook wb = getWb(path); 

        List<List<String>> list = getExcelRows(getSheet(wb,0), -1, -1);//全表读取数据

 

        int i;

        List<String> row = newArrayList<String>();

        for (i = 0; i <list.size(); i++) { 

           row= list.get(i);

           String  columnText = row.get(column); //打开具体的某一列

          

           finalOutput .add(columnText);//把这一列的数据添加到finalOutput

        }

                   return finalOutput; 

    @SuppressWarnings("static-access")

         public static void main (String args[])throws InvalidFormatException, FileNotFoundException, IOException{

    ExcelStandardHSZXD=new ExcelStandard();

    System.out.println(HSZXD.getData(0));//测试编写的方法是否有效,打印出Excel中的相关数据

    }

}


2.2 实际应用举例

2.2.1 代码实例

以下这个例子是测试某登录系统的用户名和密码有效性测试,思路是先在Excel表格中准备好能够覆盖用户名密码的有效等价类、无效等价类和边界值的测试数据。再通过设计TestNG自动化测试脚本完成登陆、判断页面是否成功登陆、退出、再登陆的页面操作。在这个过程中调用之前封装好的读写Excel代码,完成参数化的自动化测试。

代码如下:

import java.util.ArrayList;

import java.util.List;

 

importorg.apache.poi.openxml4j.exceptions.InvalidFormatException;

importorg.openqa.selenium.By;

importorg.openqa.selenium.WebDriver;

importorg.openqa.selenium.WebElement;

importorg.openqa.selenium.firefox.FirefoxDriver;

importorg.openqa.selenium.interactions.Actions;

import org.openqa.selenium.support.ui.ExpectedConditions;

importorg.openqa.selenium.support.ui.WebDriverWait;

importorg.testng.annotations.AfterClass;

importorg.testng.annotations.BeforeClass;

importorg.testng.annotations.Test;

 

public class login {

         public static  WebDriver driver;

         String baseUrl= "http://192.168.10.228";

          

  @SuppressWarnings("static-access")

@Test

  public void loginTest() throwsInterruptedException, InvalidFormatException, FileNotFoundException,IOException {

            ExcelStandard read=new ExcelStandard();//实例化一个ExcelStandard对象read,该对象能够调用ExcelStandard里所有方法

          

            List<String>input1 =new ArrayList<String>(); //创建字符串列表,存储从Excel中获取的数据

            List<String>input2=new ArrayList<String>();

            int i;

                   for(i=1;i<100;i++){

           WebElementloginelement = driver.findElement(By.id("loginAccount"));

                            WebElement loginelement2 = driver.findElement(By.id("lpassword"));

                                               WebElement element = driver.findElement(By.className("btnMain"));

                                                        WebDriverWaitwait =  new WebDriverWait(driver,10);

                                                                 wait.until(ExpectedConditions.visibilityOf(loginelement));

                                              

                                               input1=read.getData(0);//Excel列表获取第一列数据

                                               input2=read.getData(1);//Excel列表获取第二列数据

                                               loginelement.sendKeys(input1.get(i));//获取第一列数据的第i个数据

                                               loginelement2.sendKeys(input2.get(i));//获取第二列数据的第i个数据

                                    

element.click();

    Thread.sleep(5000);

    String currentUrl=driver.getCurrentUrl().toString();

    String expected="http://192.168.10.228/conference/index.html";

    //Assert.assertEquals(currentUrl,expected);

   

    if(currentUrl.equals(expected)){//判断:如果成功登陆,则退出登录系统准备下一次登陆

    WebElementshowOpt =  driver.findElement(By.id("existListid"));

                            Actions showTheOptiion = new Actions(driver);

                                     showTheOptiion.moveToElement(showOpt).perform();//将鼠标移动到系统的操作菜单展开总按钮并且悬停

                                               Thread.sleep(1000);

                                               WebElement exit=  driver.findElement(By.xpath("//ul[@class='option']/li[@id='existid']"));

                                               exit.click();

                                               Thread.sleep(3000);

                                               driver.navigate().refresh();

                                               continue;

                                              

    }

    else{ //如果未能成功登陆,则清除之前输入的数据,重新输入从Excel中获取的测试数据

    loginelement.clear();

    loginelement2.clear();

    }

                                               }

  }

  @BeforeClass

  public void beforeClass() throws InterruptedException{

           System.setProperty("webdriver.firefox.bin","G:/tools/MozillaFirefox/firefox.exe");

      driver = new FirefoxDriver();

      driver.get(baseUrl + "/");//登陆

    

  }

 

  @AfterClass

  public void afterClass() {

          //driver.quit();

          

  }

 

}

2.2.2 代码步骤解析

1.实例化对象



首先是要从ExcelStandard这个类中实例化出一个对象,该对象即能够调用ExcelStandard这个类的所有已定义的方法。

2.通过read对象调用getdata方法读取Excel数据,创建StringList,存储从Excel中获取的数据。


read.getData即通过read这个对象,调用ExcelStandard中的getData方法获取Excel表某一列的数据,

具体哪一列由getData方法的具体参数指定,参数索引从0开始,getData(0)即表示调用第一列的数据。

3.将获取到的数据填充到待测试模块中:



loginelement和loginelement2分别对应的是登录界面用户名和密码,

这里通过sendkeys方法将Excel表中获取到的数据填写进这两个输入框中。


好了介绍就到这里啦,希望能够帮助到大家,哪怕提供了一丁点帮助,笔者也是开心的~





猜你喜欢

转载自blog.csdn.net/hszxd479946/article/details/78956843