selenium自动化测试之【数据驱动测试】

数据驱动测试是自动化测试的主流设计模式之一,相同的测试脚本使用不同的测试数据来执行,测试数据和测试行为进行了完全的分离,这样的测试脚本设计模式称为数据驱动。
实施数据驱动测试的步骤:
1.编写测试脚本,脚本需要支持程序对象、文件或者数据库读入测试数据;
2.将测试脚本使用的数据测试数据存入程序对象、文件或者数据库等外部介质中;
3.运行脚本,循环调用存在外部介质的测试数据;
4.验证所有的测试结果是否符合期望的结果。

下面分别使用4种方式实现数据驱动测试
1.使用TestNG进行数据驱动测试
2.使用CSV文件进行数据驱动测试
3.使用Excel文件进行数据驱动测试
4.使用Mysql数据库实现数据的驱动测试

【一、使用TestNG进行数据驱动测试】

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

/**
 * @DataProvider注解的使用
 * 使用DataProvider提供数据有两种形式: 
 * 第一种:一种是在测试代码和测试数据放在同一个类中; 
 * 第二种:把所有的数据提供都单独写在一个类里面,当测试数据比较多时,这种方法利于维护。
 */
public class DataProviderTest {
    
    private static WebDriver driver;
    
    // @DataProvide 作为数据提供者,提供几组数组,则引用他的test方法就会执行几次
    // @DataProvide 注解定义当前方法中的返回值对象作为测试脚本的测试数据集,并将测试数据集命名为searchWords
    @DataProvider(name="searchWords")
    public static Object[][] words(){
        return new Object[][]{{"蝙蝠侠","主演","迈克尔"},{"超人","导演","唐纳"},{"生化危机","编剧","安德森"}};
    }
    
    //方法中的3个参数分别使用searchWords测试数据集中的每个一维数组中的数据进行赋值,此测试方法会被调用3次
    @Test(dataProvider="searchWords")
    public void test(String searchWords1, String searchWords2, String SearchResult){
        driver.get("http://www.baidu.com");
        driver.findElement(By.id("kw")).sendKeys(searchWords1 +" "+ searchWords2);
        driver.findElement(By.id("su")).click();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(searchWords1 +">>>>" +searchWords2+">>>>"+SearchResult);
        //判断搜索结果中是否包含测试数据中期望的关键词
        Assert.assertTrue(driver.getPageSource().contains(SearchResult));
        driver.quit();
    }
    
    @BeforeMethod
    public void beforeMethod(){
        System.setProperty("webdriver.chrome.driver", "e:\chromedriver.exe");
        driver = new ChromeDriver();
    }
}

【二、使用CSV文件进行数据驱动测试】

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

/**
 * 测试数据与测试脚本分离的方式
 */
public class DataProviderCSVTest {
    
    public static WebDriver driver;
    
    @BeforeMethod
    public void beforeMethod(){
        System.setProperty("webdriver.chrome.driver", "e:\chromedriver.exe");
        driver = new ChromeDriver();
    }
    
    
    @DataProvider(name="testData")
    public static Object[][] words() throws IOException{
        return getTestData("F://testData.csv");
    }
    
    
    @Test(dataProvider="testData")
    public void test(String searchWord1,String searchWord2,String searchResult){
        driver.get("http://www.baidu.com");
        driver.findElement(By.id("kw")).sendKeys(searchWord1+""+searchWord2);
        driver.findElement(By.id("su")).click();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Assert.assertTrue(driver.getPageSource().contains(searchResult));
        driver.quit();
    }
    
    //读取CSV文件的方法
    public static Object[][]getTestData(String fileName) throws IOException {
        //定义一个集合,存csv文件中的数据
        List<Object[]> records = new ArrayList<Object[]>();
        String record;
        BufferedReader file = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8"));
        //file.readLine(); //跳过表头, 如果不需要表头的话,不要写这句
        while((record=file.readLine())!=null){
            String fields[] = record.split(",");
            records.add(fields);
            
        }
        file.close();
        
        //定义方法的返回值,将list转换为Object二维数据
        Object[][] results = new Object[records.size()][];
        //设置二维数每行的值,每行是一个Object对象
        for(int i=0;i<records.size();i++){
            results[i] = records.get(i);
        }
        
        return results;
    }
}

【三、使用Excel文件进行数据驱动测试】

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;


/**
 * 使用Excel文件进行数据驱动测试
 * 需引入POI jar包
 * @author Administrator
 *
 */
public class DataProviderExcelTest {
    
    public static WebDriver driver;
    String url = "http://www.baidu.com";
    
    @DataProvider(name="testData")
    public static Object[][] words() throws IOException{
        return getTestData("f://","testData.xlsx","Sheet1");
    }

    @BeforeMethod
    public void beforeMethod(){
        System.setProperty("webdriver.chrome.driver", "e:\chromedriver.exe");
        driver = new ChromeDriver();
    }
    
    @AfterMethod
    public void AfterMethod(){
        driver.quit();
    }
    
    @Test(dataProvider="testData")
    public void test(String searchWord1,String searchWord2,String searchResult){
        driver.get(url);
        driver.findElement(By.id("kw")).sendKeys(searchWord1+" "+searchWord2);
        driver.findElement(By.id("su")).click();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Assert.assertTrue(driver.getPageSource().contains(searchResult));
    }
    
    //从excel中获取测试数据的方法
    public static Object[][] getTestData(String filePath,String fileName,String sheetName) throws IOException{
        //声明一个file文件对象
        File file = new File(filePath+"\"+fileName);
        //读取文件
        FileInputStream in = new FileInputStream(file);
        //声明Workbook对象
        Workbook workbook = null;
        //获取文件的扩展名
        String fileExtensionName = fileName.substring(fileName.indexOf("."));
        if(fileExtensionName.equals(".xlsx")){
            //.xlsx类型文件
            workbook = new XSSFWorkbook(in);
        }else {
            //.xls类型的文件
            workbook = new HSSFWorkbook(in);
        }
        //通过sheetName,生成Sheet对象
        Sheet sheet = workbook.getSheet(sheetName);
        //读取sheet1中数据的行数,最后一行减去第一行
        int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum();
        
        //将excel中的数据存在list中
        List<Object[]> records = new ArrayList<Object[]>();
        //遍历每行数据,去除第一行表头数据,excel的行号与列号都是从0开始
        for(int i=1;i<=rowCount;i++){
            //获取行对象
            Row row = sheet.getRow(i);
            //声明一个数组存放读取的行数据,数组大小用getlastCellNum确定
            String fields[] = new String[row.getLastCellNum()];
            //遍历每列数据
            for(int j=0;j<row.getLastCellNum();j++){
                //调用getCell与getStringCellValue方法获取excel中单元格中的数据
                fields[j] = row.getCell(j).getStringCellValue();    
            }
            records.add(fields);
        }
        
        // 定义方法的返回值,将list转换为Object二维数据
        Object[][] results = new Object[records.size()][];
        // 设置二维数每行的值,每行是一个Object对象
        for (int i = 0; i < records.size(); i++) {
            results[i] = (Object[]) records.get(i);
        }
        
        return results;
    }
}

 【四、使用Mysql数据库实现数据的驱动测试】

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;


/**
 * 使用Mysql数据库实现数据的驱动测试
 */

public class DataProviderMysqlTest {

    public WebDriver driver;
    String url = "http://www.baidu.com";
    
    @DataProvider(name="testData")
    public Object[][] words() throws IOException{
        return getTestData("search");
    }
    
    @BeforeMethod  
    public void beforeMethod(){
        System.setProperty("webdriver.chrome.driver", "e:\chromedriver.exe");
        driver = new ChromeDriver();
    }
    
    @AfterMethod
    public void afterMethod(){
        driver.quit();
    }
    
    @Test(dataProvider="testData")
    public void test(String searchWord1,String searchWord2,String searchResult){
        driver.get(url);
        driver.findElement(By.id("kw")).sendKeys(searchWord1+" "+searchWord2);
        driver.findElement(By.id("su")).click();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Assert.assertTrue(driver.getPageSource().contains(searchResult));
    }
    
    //获取Mysql数据库中的测试数据
    public static Object[][] getTestData(String tableName) throws IOException{
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/bbs";
        String username = "root";
        String password = "123";
        
        List<Object[]> records = new ArrayList<Object[]>();
        try {
            //加载数据库驱动
            Class.forName(driver);
            //获取数据库连接
            Connection connection = DriverManager.getConnection(url,username,password);
            //创建statement对象
            Statement statement = connection.createStatement();
            //准备sql语句
            String sql = "select argument1,argument2,result from " + tableName ;
            //用statement对象执行sql语句
            ResultSet rs = statement.executeQuery(sql);
            //获取ResultSetMetaData对象
            ResultSetMetaData reMetaData = rs.getMetaData();
            //调用getColumnCount()获取所有字段的数目(列数)
            int columnCount = reMetaData.getColumnCount();
            while(rs.next()){
                String fields[] = new String[columnCount];
                int column = 0;
                //遍历所有行数据的所有列数据,并存字符数组中
                for(int columnIndex = 0; columnIndex < columnCount; columnIndex ++){
                    fields[column] = rs.getString(columnIndex +1);
                    column ++;
                }
                records.add(fields);
                System.out.println(rs.getString(1)+"  "+rs.getString(2)+"   "+rs.getString(3));
                
            }
            rs.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 定义方法的返回值,将list转换为Object二维数据
        Object[][] results = new Object[records.size()][];
        // 设置二维数每行的值,每行是一个Object对象
        for (int i = 0; i < records.size(); i++) {
            results[i] = (Object[]) records.get(i);
        }
        return results;
    }
}

个人微信公众号:专注测试开发、自动化测试。

原文地址:https://www.cnblogs.com/wakey/p/10801760.html