UI自动化测试框架之Selenium关键字驱动 (转)

 

摘要

自动化测试框架demo,用关键字的形式将测试逻辑封装在数据文件中,测试工具解释这些关键字即可对其应用自动化

一、原理及特点

1.   关键字驱动测试是数据驱动测试的一种改进类型

2.    主要关键字包括三类:被操作对象(Item)、操作(Operation)和值(value),用面向对象形式可将其表现为Item.Operation(Value)

3.   将测试逻辑按照这些关键字进行分解,形成数据文件。

4.    用关键字的形式将测试逻辑封装在数据文件中,测试工具只要能够解释这些关键字即可对其应用自动化

二、准备

使用工具:eclipse

用到的第三方jar包:poi.jar(操作excel);selenium.jar

理解难点:java反射机制;逐步分层

三、框架构思

1、编写脚本

首先我们来写一个登陆开源中国的脚本

public class Login_Script {
            public static WebDriver driver=null;             public static void main(String []agrs) throws InterruptedException{ //                启动火狐浏览器                 driver= new FirefoxDriver(); //                最大化                 driver.manage().window().maximize(); //                打开开源中国网址                 driver.get("http://www.oschina.net/"); //                点击登录                 driver.findElement(By.xpath("//*[@id='OSC_Userbar']/a[1]")).click(); //                输入用户名                 driver.findElement(By.xpath("//*[@id='f_email']")).sendKeys("XXXXXXB"); //                输入密码                 driver.findElement(By.xpath("//*[@id='f_pwd']")).sendKeys("XXXXXXXA"); //                点击登录按钮 //                driver.findElement(By.xpath("//*[@id='login_osc']/table/tbody/tr[7]/td/input")).click(); //                Thread.sleep(30); //                点击退出按钮                 driver.findElement(By.xpath("//*[@id='OSC_Userbar']/a[3]")).click(); //                关闭浏览器                 driver.quit();                 } }
2、脚本分析

这是登陆的场景

操作步骤

第一步:启动浏览器

第二步:输入网址

第四步:点击登录

第五步:输入用户名

第六步:输入密码

第七步:点击登录按钮

第八步:点击退出

第九步:关闭浏览器

3、使用excel

建立一个excel

在java中创建一个操作excel的类 ,主要实现是对excel的读和写,主要代码如下:

public class ExcelUtils {         public static HSSFSheet ExcelSheet;         public static HSSFWorkbook    ExcelBook;         public static HSSFRow Row;         public static HSSFCell    Cell;         public static void setExcelFile(String Path,String    SheetName) throws Exception{             FileInputStream    ExcelFile=new FileInputStream(Path);             ExcelBook=new HSSFWorkbook(ExcelFile);             ExcelSheet=ExcelBook.getSheet(SheetName);                 }         public static void setCellData(String Result,  int RowNum, int ColNum,String Path) throws Exception{               Row  = ExcelSheet.getRow(RowNum);             Cell = Row.getCell(ColNum, Row.RETURN_BLANK_AS_NULL);             if (Cell == null) {                 Cell = Row.createCell(ColNum);                 Cell.setCellValue(Result);                 } else {                     Cell.setCellValue(Result);                 }             FileOutputStream fileOut = new FileOutputStream(Path);             ExcelBook.write(fileOut);             fileOut.flush();             fileOut.close();         }         public static String getCellDate(int RowNum,int CloNum){             Cell=ExcelSheet.getRow(RowNum).getCell(CloNum);             String cellData=Cell.getStringCellValue();             return cellData;         } }
4、新建一个ActionKeyWords类
public class ActionKeyWords {
    public static WebDriver driver=null; //    启动浏览器并最大化     public static void OpenBrowser (){         driver= new FirefoxDriver();         driver.manage().window().maximize();     } //    打开开源中国网址     public static void Navigate (){         driver.get("http://www.oschina.net/");     } //    点击登录     public static void Login_Click (){         driver.findElement(By.xpath("//*[@id='OSC_Userbar']/a[1]")).click();     } //    输入用户名     public static void Input_Name (){         driver.findElement(By.xpath("//*[@id='f_email']")).sendKeys("XXXXXXA");     } //    输入密码     public static void Input_Password (){         driver.findElement(By.xpath("//*[@id='f_pwd']")).sendKeys("XXXXXXB");     } //    点击登录按钮     public static void Login_Button (){         driver.findElement(By.xpath("//*[@id='login_osc']/table/tbody/tr[7]/td/input")).click();     }     //    点击退出按钮     public static void Logout_Click (){         driver.findElement(By.xpath("//*[@id='OSC_Userbar']/a[3]")).click();     } //    关闭浏览器     public static void CloseBrowser (){         driver.quit();     } }
5、修改Login_Script脚本.
public class Login_Script {
            public static void main(String []agrs) throws Exception{                 ExcelUtils.setExcelFile("D:\\data\\TestData.xls", "steps");                 ActionKeyWords actionKeyWords= new ActionKeyWords();                 String Keywords=null;                 for(int RowNum=1;RowNum<=ExcelUtils.getLastRowNums();RowNum++){                     Keywords=ExcelUtils.getCellDate(RowNum, 3);                     if(Keywords.trim().equals("OpenBrowser")){                         actionKeyWords.OpenBrowser();                     }else if(Keywords.trim().equals("Navigate")){                         actionKeyWords.Navigate();                     }else if(Keywords.trim().equals("Login_Click")){                         actionKeyWords.Login_Click();                     }else if(Keywords.trim().equals("Input_Name")){                         actionKeyWords.Input_Name();                     }else if(Keywords.trim().equals("Input_Password")){                         actionKeyWords.Input_Password();                     }else if(Keywords.trim().equals("Login_Button")){                         actionKeyWords.Login_Button();                     }else if(Keywords.trim().equals("Logout_Click")){                         actionKeyWords.Logout_Click();                     }else if(Keywords.trim().equals("CloseBrowser")){                         actionKeyWords.CloseBrowser();                     }                 }             } }

这样代码的框架就基本已经搭建起来了,代码结构如下:

四、结构优化

1、优化Login_Script 类中的代码

注:这里用到了反射机制

 public class Login_Script {             public static ActionKeyWords actionKeyWords;             public static String Keywords=null;             public static Method[] method;             public Login_Script(){                 actionKeyWords= new ActionKeyWords();                 method=actionKeyWords.getClass().getMethods();             }             public static void main(String []agrs) throws Exception{                 ExcelUtils.setExcelFile("D:\\data\\TestData.xls", "steps");                 new Login_Script();                 for(int RowNum=1;RowNum<=ExcelUtils.getLastRowNums();RowNum++){                     Keywords=ExcelUtils.getCellDate(RowNum, 3);                     login_action();                 }             }             public static void login_action(){                 for(int i=0;i<method.length;i++){ //                    System.out.println(method[i].getName()+"     "+actionKeyWords+Keywords);                     if(method[i].getName().trim().equals(Keywords)){                         try {                             method[i].invoke(actionKeyWords);                         } catch (IllegalAccessException e) {                             // TODO Auto-generated catch block                             e.printStackTrace();                         } catch (IllegalArgumentException e) {                             // TODO Auto-generated catch block                             e.printStackTrace();                         } catch (InvocationTargetException e) {                             // TODO Auto-generated catch block                             e.printStackTrace();                         }                     }                 }             } }
2、将程序中的常量统一管理

例如:网页的地址,账户、密码,excel路径,这里我们在文件下面建立一个

public class Contants {
    public static  String url="http://www.oschina.net/";     public static String excelFile="D:\\data\\";     public static String excelName="TestData.xls";     public static String excelSheet="steps";     public static int excelKWCloNum=3;     public static String userName="XXXXXXXA";     public static String userPassword="XXXXXB"; }
3、增加对象库

下面我们看一下ActionKeyWords类中定位元素的路径 是在代码里面的,如果每次去修改的定位路径的是时候都要修改代码,为了便于维护,我们将这些元素的对象放在一个文件中,同时我们在Excel增加一列 Page Objects,这样程序根据Excel中的Page Objects,去文件中读取相应的元素,这里我们增加一个类OrpUtil,读取元素的对象 

# Home Page Objects
Userbar_login=//*[@id='OSC_Userbar']/a[1]
Userbar_logout=//div[@id='OSC_Userbar']/a[3] #Login Page Objects Input_name=//*[@id='f_email'] Input_password=//*[@id='f_pwd'] Login_button=//*[@id='login_osc']/table/tbody/tr[7]/td/input
//OrpUtil类
public class OrpUtil {     public static String  readValue(String a){         Properties pro=new Properties();         String popath=Contants.ObjectReUrl;         String value=null;         try {             InputStream in =new BufferedInputStream(new FileInputStream(popath));             pro.load(in);             value=pro.getProperty(a);         } catch (FileNotFoundException e) {             // TODO Auto-generated catch block             e.printStackTrace();         }catch (IOException e) {             // TODO Auto-generated catch block             e.printStackTrace();         }         return value;     } }

优化后的ActionKeyWords类

public class ActionKeyWords {
    public static WebDriver driver=null; //    启动浏览器并最大化     public static void OpenBrowser (String OR){         System.setProperty("webdriver.chrome.driver", ".//server//chromedriver.exe");         driver= new ChromeDriver();         driver.manage().window().maximize();     } //    打开开源中国网址     public static void Navigate (String OR){         driver.get(Contants.url);     } //    点击登录     public static void Login_Click (String OR){         driver.findElement(By.xpath(OrpUtil.readValue(OR))).click();     } //    输入用户名     public static void Input_Name (String OR){         driver.findElement(By.xpath(OrpUtil.readValue(OR))).clear();         driver.findElement(By.xpath(OrpUtil.readValue(OR))).sendKeys(Contants.userName);     } //    输入密码     public static void Input_Password (String OR){         driver.findElement(By.xpath(OrpUtil.readValue(OR))).click();         driver.findElement(By.xpath(OrpUtil.readValue(OR))).sendKeys(Contants.userPassword);     } //    点击登录按钮     public static void Login_Button (String OR){         driver.findElement(By.xpath(OrpUtil.readValue(OR))).click();     }     //    点击退出按钮     public static void Logout_Click (String OR){         try {             Thread.sleep(300);             driver.findElement(By.xpath(OrpUtil.readValue(OR))).click();         } catch (InterruptedException e) {             // TODO Auto-generated catch block             e.printStackTrace();         }     } //    关闭浏览器     public static void CloseBrowser (String OR){         driver.quit();     } }

这个OR的值是从Excel中读取的

 

 

4、增加测试场景

从Excel中我们可以看到,这操作是对应的用例编写中的我们的操作步骤,在用例设计的时候还有测试场景和结果,这里

我们先增加个场景在EXCEL中增加一个名称为Suite的Sheet页

我们程序的运行逻辑是循环读取Suite页中的Runmode,当为YES时根据对应的TestSuiteID去读取对应的Steps页中的操作在步骤,进行运行

public static void main(String []agrs) throws Exception{ ExcelUtils.setExcelFile(Contants.excelFile+Contants.excelName ); new Login_Script(); bResult = true; // 循环读取suitSheet里面的值,找出运行的场景 for(int j=1;j<=ExcelUtils.getLastRowNums(Contants.suitSheet);j++){ String Runmode=ExcelUtils.getCellDate(j, Contants.suitRunmode,Contants.suitSheet); String suitTestSuiteId=ExcelUtils.getCellDate(j, Contants.suitTestSuiteId,Contants.suitSheet); int sRowNum; if(Runmode.equals("YES")){ // 根据stepTestSuiteId在caseSheet中循环查找相对应的执行步骤 for(sRowNum=1;sRowNum<=ExcelUtils.getLastRowNums(Contants.caseSheet);sRowNum++){ String stepTestSuiteId=ExcelUtils.getCellDate(sRowNum, Contants.stepTestSuiteId,Contants.caseSheet); System.out.println(ExcelUtils.getCellDate(sRowNum, Contants.excelKWCloNum,Contants.caseSheet)); if(stepTestSuiteId.trim().equals(suitTestSuiteId)){ Keywords=ExcelUtils.getCellDate(sRowNum, Contants.excelKWCloNum,Contants.caseSheet); r=ExcelUtils.getCellDate(sRowNum, Contants.excelPOCloNum,Contants.caseSheet); login_action(sRowNum); if(bResult == false){ ExcelUtils.setCellData(Contants.fail, j, Contants.suitResult,Contants.excelFile+Contants.excelName, Contants.suitSheet); } } } if(bResult == true){ ExcelUtils.setCellData(Contants.pass, j, Contants.suitResult,Contants.excelFile+Contants.excelName, Contants.suitSheet); } }else{ System.out.println("没有要执行的用例"); break; } } }

 

5、增加测试结果

在Excel中新增一列Resut

 

在Login_Script中定义一个boolean类型的变量bResult,默认是true在各个地方try,,cacth,当出现异常的时候在bResult赋值为false,在Excel工具类中增加一个写入excel值得方法

五、小结

这样我们的关键字驱动框架就初步搭好了,下面我们回归一下基本思路:

        

转自:http://my.oschina.net/hellotest/blog/531932

转载于:https://www.cnblogs.com/dengnapianhuahai/p/5609419.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
适合人群:【学习前提】 1. 具备python3语言基础 【学习人群】 1. 手工测试人员学习UI自动化测试技能 2. 开发人员测试开发岗位 3. 如具有丰富的自动化测经验,本课程可能并不满足你学习计划:1.下载课程中配套的软件资料 2.结合课件中Demo可完成学习任务课程目标:掌握UI自动化测试框架的设计与实现课程简介:UI自动化框架的设计需储备基础知识,方能完成自动化测试框架的实现,如数据驱动、日志、配置文件等AutoUiTestFrame自动化框架的目录结构初步进行规划,目录结构如下:Config 配置文件的目录v  config.ini 配置文件;v  globalconfig.py 获得日志路径、测试用例路径、测试报告路径、测试数据路径;v  Data 测试数据;v  TestData.xlsx 测试数据。Public 公共文件库v  Common 封装的公共的方法n  Commonconfig.py 公共的参数配置:调试过程中的测试数据等;n  DoExcel.py 操作excel(数据驱动);n  Send_mail.py 发送邮件(html);n  ReadConfigIni.py 读取ini格式的配置文件;n  TestCaseInfo.py  测试用例信息;n  Log.py 日志类。设置日志类,其他模块或文件需要日志类时,调用该文件。v  Pages 使用po模式设计的测试页面n  BasePage.py  基类,对一些测试页面公共方法、属性的封装及webdrive一些方法的二次封装;n  Bing.py 测试页面。Report 测试报告v  Log 日志目录n  *****log日志。v  TestReport 测试报告目录n  ***html测试报告。TestCase 测试用例v  TC_bing.py。Run.py  控制测试用例的运行。
Selenium是一个自动化测试工具,它可以模拟用户在浏览器中的行为,通过编写脚本来实现自动化测试。在使用Selenium进行测试时,需要编写大量的代码,而关键字驱动测试框架可以简化这一过程,将测试流程封装成一系列的关键字,使得测试人员只需要编写简单的关键字,就可以完成复杂的测试任务。 下面是一个简单的Python封装Selenium关键字驱动测试框架的示例: ``` # 导入Selenium相关库 from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 定义关键字驱动测试框架 class SeleniumDriver: def __init__(self, browser="chrome"): if browser == "chrome": self.driver = webdriver.Chrome() elif browser == "firefox": self.driver = webdriver.Firefox() else: self.driver = webdriver.Chrome() def open_url(self, url): self.driver.get(url) def click_element(self, locator): element = self.wait_for_element(locator) element.click() def input_text(self, locator, text): element = self.wait_for_element(locator) element.send_keys(text) def wait_for_element(self, locator, timeout=10): return WebDriverWait(self.driver, timeout).until( EC.presence_of_element_located(locator) ) def quit(self): self.driver.quit() # 使用示例 driver = SeleniumDriver() driver.open_url("https://www.baidu.com") driver.input_text((By.ID, "kw"), "Python") driver.click_element((By.ID, "su")) driver.quit() ``` 在这个示例中,我们定义了一个名为`SeleniumDriver`的类,它封装了常用的Selenium操作,包括打开URL、点击元素、输入文本等。我们可以通过使用这些关键字,快速编写自动化测试脚本。 在使用这个测试框架时,我们首先需要创建一个`SeleniumDriver`对象,然后调用`open_url`方法打开目标网页,接着使用`input_text`方法输入搜索关键字,最后调用`click_element`方法点击搜索按钮。在执行完毕后,我们需要调用`quit`方法关闭浏览器。 这个示例只是一个非常简单的封装,实际使用时可能需要根据具体需求进行修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值