【软件测试】实验2——selenium的使用及WebDriver的编程

Posted on 2018-04-19 10:54  XieJuan  阅读(388)  评论(0)    收藏  举报

一、 实验要求

 

 

二、 实验过程

1.  实验环境配置——seleniumIDE

该实验进行的环境为

操作系统:Windows 10 专业版,64位操作系统,基于x64的处理器

处理器:Intel(R) Core(TM) i5-5200U CPU @ 2.20GHz 2.19GHz

1.1     下载浏览器

方案一:选用Firefox

考虑到使用selenium 插件并得到WebDriver 文件,然而与最新版的Firefox 适配的插件并不能成功导出java 文件,因此,Firefox 需要使用较老的版本,这里使用老师建议的42.0版本。

Firefox 所有版本的下载地址:http://ftp.mozilla.org/pub/firefox/releases/

方案二:使用Chrome 浏览器

下载最新版本即可

1.2    安装 seleniumIDE 插件

对于Firefox :

在菜单栏中找到“添加组件”

并在搜索框中搜索“selenium”,在搜索结果最下面点击“查看更多”将会出现一个新的页面

选取第一个结果“Selenium IDE”,点击会进入新的页面,选取合适的版本即可。

对于Chrome 浏览器

进入谷歌应用商店,搜索selenium。

Selenium 本来是针对于Firefox 发布的,因此有另一个版本的插件是可以在Chrome上使用的,搜索结果中会出现,它叫Katalon Recorder(selenium for Chrome)。下载这个版本并安装就可以了。

网址:http://www.google.cn/chrome/webstore/extensions.html

1.3使用seleniumIDE 录制脚本并导出脚本

我使用的是Chrome,其实插件使用方式是一样的,因此在这里也就只讲Chrome是怎么录制的了。

首先,在浏览器菜单栏中找到Katalon Recorder并打开

其次,新建一个testsuite, 第一次新建,会自动生成一个test case。

然后,点击菜单栏中的 record, 打开你的目标网页进行操作,此时Katalon Recorder右侧会有相应的结果出现。

在这里有一个需要注意的地方是,我们后面需要测试数据的匹配情况,因此对于登录成功后的值需要进行存储。在这里可以在你需要匹配的文本区域右键,选择 Katalon Recorder工具——> assert text.

然后,停止录制,可以点击菜单栏的运行,看一下Katalon Recorder 的自动运行情况。

最后,将test case 导出,选择Java(WebDriver + JUnit)格式存储。

2. 编写WebDriver 程序,测试数据

2.1 编写Excel文件读写程序

2.1.1 环境配置

下载程序会涉及的jar 包,去官网,或者http://mvnrepository.com/下载即可。

  1.commons-collections4-4.1.jar

  2.poi-3.17-beta1.jar

  3.poi-ooxml-3.17-beta1.jar

  4.poi-ooxml-schemas-3.17-beta1.jar

  5.xmlbeans-2.6.0.jar

2.1.2 编写程序——源代码

package cn.tju.jane;
/**
 * @author Jane
 */

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
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;

public class GetCheckInfo {
    Workbook wb = null;
    Sheet sheet = null;
    Row row = null;
    List<Map<String, String>> list = null;
    String url = null;
    String username = null;
    String filePath = "E:\\input.xlsx";
    String columns[] = { "number", "url" };

    public  Map<String, String> getExcelValue() {
        wb = readExcel(filePath);
        Map<String, String> map = new LinkedHashMap<String, String>();
        if (wb != null) {
            // 用来存放表中数据
            list = new ArrayList<Map<String, String>>();
            // 获取第一个sheet
            sheet = wb.getSheetAt(0);
            // 获取最大行数
            int rownum = sheet.getPhysicalNumberOfRows();
            // 获取第一行
            row = sheet.getRow(0);
            // 获取最大列数
            int colnum = row.getPhysicalNumberOfCells();

            for (int i = 0; i < rownum; i++) {
                row = sheet.getRow(i);
                if (row != null) {
                    username = (String) getCellFormatValue(row.getCell(0));
                    url = (String) getCellFormatValue(row.getCell(1));
                    map.put(username, url);

                } else {
                    break;
                }
                //list.add(map);
            }
        }

        return map;
    }

    // 读取excel
    public static Workbook readExcel(String filePath) {
        Workbook wb = null;
        if (filePath == null) {
            return null;
        }
        String extString = filePath.substring(filePath.lastIndexOf("."));
        InputStream is = null;
        try {
            is = new FileInputStream(filePath);
            if (".xls".equals(extString)) {
                return wb = new HSSFWorkbook(is);
            } else if (".xlsx".equals(extString)) {
                return wb = new XSSFWorkbook(is);
            } else {
                return wb = null;
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wb;
    }

    @SuppressWarnings("deprecation")
    public static Object getCellFormatValue(Cell cell) {
        Object cellValue = null;
        if (cell != null) {
            // 判断cell类型
            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC: {
                cellValue = String.valueOf(cell.getNumericCellValue());
                break;
            }
            case Cell.CELL_TYPE_FORMULA: {
                // 判断cell是否为日期格式
                if (DateUtil.isCellDateFormatted(cell)) {
                    // 转换为日期格式YYYY-mm-dd
                    cellValue = cell.getDateCellValue();
                } else {
                    // 数字
                    cellValue = String.valueOf(cell.getNumericCellValue());
                }
                break;
            }
            case Cell.CELL_TYPE_STRING: {
                cellValue = cell.getRichStringCellValue().getString();
                break;
            }
            default:
                cellValue = "";
            }
        } else {
            cellValue = "";
        }
        return cellValue;
    }
}

2.2 编写WebDriver 程序

2.2.1 环境配置

下载程序需要的jar包

  1. selenium-server-standalone-2.53.1.jar
  2. selenium-java-2.53.1.jar
  3. selenium-java-2.53.1-srcs.jar

下载地址:http://selenium-release.storage.googleapis.com/index.html

2.2.2 编写程序——源代码

package cn.tju.jane;

/**

 * @author Jane

 *

 */

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import java.util.concurrent.TimeUnit;

import org.junit.*;

import static org.junit.Assert.*;

import org.openqa.selenium.*;

import org.openqa.selenium.firefox.FirefoxDriver;

import java.io.IOException;

 

public class Testlab {

      private WebDriver driver;

      private String baseUrl;

      private boolean acceptNextAlert = true;

      private StringBuffer verificationErrors = new StringBuffer();

      private GetCheckInfo getinfo = new GetCheckInfo();

 

      @Before

      public void setUp() throws Exception {

           driver = new FirefoxDriver();

           baseUrl = "https://www.katalon.com/";

           driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

 

      }

 

      @Test

 

      public void testLab() throws Exception {

           String username, url;

 

           Map<String, String> map = getinfo.getExcelValue();

 

     

                 for (Entry<String, String> entry : map.entrySet()) {

                      username = entry.getKey();

                      url = entry.getValue();

                      if (username.isEmpty()) {

                            System.out.println("The username is null");

 

                      } else if (url.isEmpty()) {

                            System.out.println("The url is null");

 

                      } else {

                            username = username.trim();

                            url = url.trim();

                            driver.get("https://psych.liebes.top/st");

                            driver.findElement(By.id("username")).click();

                            driver.findElement(By.id("username")).clear();

                            driver.findElement(By.id("username")).sendKeys(username);

                            driver.findElement(By.id("password")).click();

                            driver.findElement(By.id("password")).clear();

                            driver.findElement(By.id("password")).sendKeys(username.substring(username.length() - 6));

                            driver.findElement(By.id("submitButton")).click();

                            assertEquals(url, driver.findElement(By.xpath("//p")).getText());

 

                      }

                 }

           }

      }

 

      @After

      public void tearDown() throws Exception {

           driver.quit();

           String verificationErrorString = verificationErrors.toString();

           if (!"".equals(verificationErrorString)) {

                 fail(verificationErrorString);

           }

      }

 

      private boolean isElementPresent(By by) {

           try {

                 driver.findElement(by);

                 return true;

           } catch (NoSuchElementException e) {

                 return false;

           }

      }

 

      private boolean isAlertPresent() {

           try {

                 driver.switchTo().alert();

                 return true;

           } catch (NoAlertPresentException e) {

                 return false;

           }

      }

 

      private String closeAlertAndGetItsText() {

           try {

                 Alert alert = driver.switchTo().alert();

                 String alertText = alert.getText();

                 if (acceptNextAlert) {

                      alert.accept();

                 } else {

                      alert.dismiss();

                 }

                 return alertText;

           } finally {

                 acceptNextAlert = true;

           }

      }

}

三、 实验结果

最后运行程序就可以得到实验的结果啦,由于结果里面涉及隐私,我就不po 出来啦。

四、 遇到的问题

  1. Selenium IDE 插件安装问题,Firefox 版本更新后,直接的selenium IDE 插件没有导出文件的地方,找插件找了很久。
  1. Jar 包不全,程序无法正常运行。最后通过询问同学,百度相关问题,找到问题所在,下载所缺jar包,最后能成功运行
  2. 读取Excel 文件数据时数据存储格式错误,导致测试时无法正常准确的测试。由于第一次存储数据的数据结构不正确,加载数据时方式也不对,导致测试无法停止。

五、 实验感悟

  1. Selenium自动测试更重要的应该是它的WebDriver, 插件的安装的必要性在于可以参考其标准的WebDriver 文件的编程结构。
  2. 多尝试,多百度,多思考。

六、 最后说一点

  其实实验做完你会发现,其实Firefox 版本不重要,seleniumIDE 他都有做适配的版本,由于Chrome 比较厉害,普及率很高,seleniumIDE 也做了适配版本。使用插件的目的是为了获得他的WebDriver 程序,毕竟人家的是要标准些,然后对他的程序进行修改,你就可以做你想做的事情了。

  总的来说,等你把实验都做了一遍之后,发现,其实这个实验不难,难的是下一个。

  加油吧。