Selenium页面对象模型

1、Selenium页面对象模型

优点
页面的对象模型是其中测试对象和功能被彼此分开,从而保持代码干净的实现。
对象保持独立的测试脚本。一个目的可以通过一个或多个测试脚本进行访问,因此,POM可以帮助我们创建对象一次和多次使用。
由于创建对象后,很容易访问和易于更新一个对象的特定属性。

POM流程图

2、使用Excel数据驱动
在设计测试,参数化测试是不可避免的。我们会利用Apache的POI- Excel JAR实现是一样的。它可以帮助我们来读取和写入到Excel中。
下载JAR
第1步:导航到URL- http://poi.apache.org/download.htmll并下载ZIP格式。

第2步:点击镜像链接下载JAR。

第3步:解压缩到一个文件夹

第4步:如下所示的解压缩后的内容将被显示。

第5步:现在创建一个新的项目,并在“External JARs”添加“POI-3.10.FINAL”文件夹中所有的jar包

第6步:现在,添加所有的“External JARs”在“OOXML-LIB”文件夹中。

第7步:现在,添加所有的“External JARs”在“lib”文件夹中。

第8步:如下图所示,显示已添加的JAR文件。

第9步:如下图所示的Package Explorer显示。此外附加“webdriver”相关的JAR

实际使用
http://www.yiibai.com/selenium/selenium_parameterizing_using_excel.html

3、log4j日志

http://www.yiibai.com/selenium/selenium_log4j_logging.html#article-start
让我们来了解应用程序运行。
日志输出可以保存,可以在以后进行分析。
有助于调试,以防自动化测试失败
也可用于审计目的看应用的健康。
组件
1,Logger类的实例。
2,用于记录该消息为以下之一日志级别的方法
error
warn
info
debug
log

第1步:从https://logging.apache.org/log4j/1.2/download.htmll下载log4j的JAR文件,并将下载JAR文件的解压缩格式。

第2步:通过浏览到文件菜单中创建'New Java Project'。

第3步:输入项目的名称为“log4j_demo”,然后单击“Next”

第4步:单击添加外部JAR,并添加“Log4j-1.2.17.jar”

第5步:单击添加外部JAR,并添加Selenium webdriver的类库。

第6步:单击添加外部JAR,并添加Selenium webdriver的JAR文件的位于libs文件夹中。

第7步:使用它我们可以指定Log4j的属性添加一个新的XML文件。

第8步:输入日志文件的名称为“log4j.xml”。

第9步:下面的最终文件夹结构如下所示。

第10步:现在增加Log4j 这将被记录执行过程中的性能。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false"><appender name="fileAppender" class="org.apache.log4j.FileAppender"><param name="Threshold" value="INFO" /><param name="File" value="percent_calculator.log"/><layout class="org.apache.log4j.PatternLayout"><param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss}  [%c] (%t:%x) %m%n" /></layout></appender><root><level value="INFO"/><appender-ref ref="fileAppender"/></root>
</log4j:configuration>

第11步:现在用于演示的目的,我们将结合log4j在相同的测试,我们已经完成(百分比计算器)。添加一个类文件“Main”方法功能

执行
在执行日志文件的根文件夹中创建如下图所示。在Eclipse中不能找出文件。应该打开“Windows资源管理器”来显示相同。

该文件的内容如下所示。

4、异常处理

当我们正在开发测试中,我们要确保,即使测试失败的脚本可以继续执行。如果最坏的情况都处理不好意外的异常会被抛出。
如果发生异常,由于无法找到元素,或者预期的结果不与实际值相符,我们应该抓住这个异常并结束测试的逻辑方式,以防脚本本身突然终止。
语法
实际的代码应该放在try块和异常后的动作应该放在catch块。请注意:“finally'块就算没有问题,不管脚本是否已经被抛出的异常都会执行。

try
{    //Perform Action
}
catch(ExceptionType1 exp1)
{    //Catch block 1
}
catch(ExceptionType2 exp2)
{    //Catch block 2
}
catch(ExceptionType3 exp3)
{    //Catch block 3
}
finally
{    //The finally block always executes.
}    

public static WebElement lnk_percent_calc(WebDriver driver)throws Exception
{try{element = driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a"));return element;}catch (Exception e1){// Add a message to your Log File to capture the errorLogger.error("Link is not found.");// Take a screenshot which will be helpful for analysis.File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);FileUtils.copyFile(screenshot, new File("D:frameworkscreenshots.jpg")); throw(e1);}
}

5、多浏览器测试

用户可以同时执行多个浏览器中的脚本。
http://www.yiibai.com/selenium/selenium_multi_browser_testing.html

@Parameters("browser")@BeforeTestpublic void launchapp(String browser) {             if (browser.equalsIgnoreCase("firefox")) {System.out.println(" Executing on FireFox");driver = new FirefoxDriver();driver.get(URL);driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);driver.manage().window().maximize();           } else if (browser.equalsIgnoreCase("chrome")) {System.out.println(" Executing on CHROME");System.out.println("Executing on IE");System.setProperty("webdriver.chrome.driver", "D:chromedriver.exe");driver = new ChromeDriver();driver.get(URL);driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);driver.manage().window().maximize();   } else if (browser.equalsIgnoreCase("ie")) {System.out.println("Executing on IE");System.setProperty("webdriver.ie.driver", "D:IEDriverServer.exe");driver = new InternetExplorerDriver();driver.get(URL);driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);driver.manage().window().maximize();           }else {throw new IllegalArgumentException("The Browser Type is Undefined");}}

创建一个XML这将有助于我们在参数设置浏览器的名字,不要忘记提及 parallel="tests"为了同时在所有浏览器中执行。

通过对XML文件进行右键点击执行脚本,然后选择 'Run As' >> 'TestNG' 方式,如下图所示。

输出
所有的浏览器将平行展开,结果将被打印在控制台上。
注:对于我们在IE浏览器执行成功确保复选框“启用保护模式”下的“IE选项中的安全选项卡中选中或未在所有区域中未检查。

TestNG的结果以HTML格式来查看详细的分析。

6、捕捉屏幕截图
截图捕获功能可以帮助我们在需要在运行时抓取截图,在特别是当故障发生。随着截图的帮助和日志信息,我们将能够更好地分析结果
截图是本地执行和Selenium 网格(远程)处决配置不同。让我们来看看他们每一个例子

本地主机执行
我们将计算百分比之后的截图。请确保给一个有效的路径,用以保存屏幕截图。

File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("D:screenshotsscreenshots1.jpg")); 

输出 

在执行这个脚本,截图保存在“D:screenshots”文件夹中名为'screenshots1.jpg“,如下图所示。

Selenium网格- 捕捉屏幕截图
当Selenium网格工作,我们应该确保从远程系统采取正确的截图。我们将充分利用增强的驱动程序。
我们将连接到集线器Firefox的节点上执行该脚本。更多关于配置集线器和节点,请参阅Selenium网格章节。

package TestNG;    import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.TakesScreenshot;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import java.io.File;
import java.net.URL;
import java.net.MalformedURLException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.io.IOException;    public class TestNGClass
{    public WebDriver driver;    public String URL, Node;    protected ThreadLocal<RemoteWebDriver> threadDriver = null;    @Parameters("browser")    @BeforeTest    public void launchapp(String browser) throws MalformedURLException    {                 String URL = "http://www.calculator.net";    if (browser.equalsIgnoreCase("firefox"))     {    System.out.println(" Executing on FireFox");    String Node = "http://10.112.66.52:5555/wd/hub";    DesiredCapabilities cap = DesiredCapabilities.firefox();    cap.setBrowserName("firefox");    driver = new RemoteWebDriver(new URL(Node), cap);    //Puts a Implicit wait, Will wait for 10 seconds before throwing exception    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);    //Launch website
         driver.navigate().to(URL);         driver.manage().window().maximize();               }     else     {    throw new IllegalArgumentException("The Browser Type is Undefined");    }    }    @Test    public void calculatepercent() throws IOException    {    driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click();      // Click on Math Calculators      driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a")).click();     // Click on Percent Calculators    // Make use of augmented Driver to capture Screenshots.    WebDriver augmentedDriver = new Augmenter().augment(driver);    File screenshot = ((TakesScreenshot)augmentedDriver).getScreenshotAs(OutputType.FILE);    FileUtils.copyFile(screenshot, new File("D:screenshots
emotescreenshot1.jpg"));    // Please note - Screenshot would be saved on the system where the script is executed and NOT on remote machine.
                    driver.findElement(By.id("cpar1")).sendKeys("10");          // Enter value 10 in the first number of the percent Calculator    driver.findElement(By.id("cpar2")).sendKeys("50");          // Enter value 50 in the second number of the percent Calculator        driver.findElement(By.xpath(".//*[@id='content']/table/tbody/tr/td[2]/input")).click();         // Click Calculate Button    String result = driver.findElement(By.xpath(".//*[@id='content']/p[2]/span/font/b")).getText();                 // Get the Result Text based on its xpath        System.out.println(" The Result is " + result);                                     //Print a Log In message to the screen    if(result.equals("5"))    {    System.out.println(" The Result is Pass");    }    else    {    System.out.println(" The Result is Fail");    }                   }    @AfterTest    public void closeBrowser()     {    driver.quit();               }
}    

输出
当执行该脚本,截图被捕获并储存在指定的位置,如下所示。

7、捕捉视频
有时候我们未必能够分析故障只需用日志文件或截图的帮助。有时捕获完整的执行视频帮助。让我们了解如何捕捉视频。
配置
第1步:导航到URL - http://www.randelshofer.ch/monte/index.htmll和下载屏幕记录JAR,如下图所示。

 第2步:下载后,添加JAR文件添加到当前项目的库。

第3步:我们会利用Java的AWT包来初始化显卡配置。

GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();

第4步:它采用下列参数创建ScreenRecorder的一个实例。

示例
我们将捕获简单的测试执行视频 - 百分比计算。

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
import org.monte.media.math.Rational;
import org.monte.media.Format;
import org.monte.screenrecorder.ScreenRecorder;
import static org.monte.media.AudioFormatKeys.*;
import static org.monte.media.VideoFormatKeys.*;
import java.awt.*;                            public class webdriverdemo
{                            private static ScreenRecorder screenRecorder;                            public static void main(String[] args) throws IOException, AWTException                            {                            GraphicsConfiguration gconfig = GraphicsEnvironment                            .getLocalGraphicsEnvironment()                            .getDefaultScreenDevice()                            .getDefaultConfiguration();                            screenRecorder = new ScreenRecorder(gconfig,                            new Format(MediaTypeKey, MediaType.FILE, MimeTypeKey,                            MIME_AVI),                            new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey,                            ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,                            CompressorNameKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,                            DepthKey, (int)24, FrameRateKey, Rational.valueOf(15),                            QualityKey, 1.0f,                            KeyFrameIntervalKey, (int) (15 * 60)),                            new Format(MediaTypeKey, MediaType.VIDEO,                            EncodingKey,"black",                            FrameRateKey, Rational.valueOf(30)), null);                            WebDriver driver = new FirefoxDriver();                            // Start Capturing the Video
        screenRecorder.start();                            //Puts a Implicit wait, Will wait for 10 seconds before throwing exception                            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);                            //Launch website                            driver.navigate().to("http://www.calculator.net/");                            //Maximize the browser
        driver.manage().window().maximize();                            // Click on Math Calculators                            driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click();                            // Click on Percent Calculators                            driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a")).click();                            // Enter value 10 in the first number of the percent Calculator                            driver.findElement(By.id("cpar1")).sendKeys("10");                            // Enter value 50 in the second number of the percent Calculator                            driver.findElement(By.id("cpar2")).sendKeys("50");                            // Click Calculate Button                            driver.findElement(By.xpath(".//*[@id='content']/table/tbody/tr/td[2]/input")).click();                            // Get the Result Text based on its xpath                            String result = driver.findElement(By.xpath(".//*[@id='content']/p[2]/span/font/b")).getText();                            File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);                            FileUtils.copyFile(screenshot, new File("D:screenshotsscreenshots1.jpg"));                                  //Print a Log In message to the screen                            System.out.println(" The Result is " + result);                            //Close the Browser.
    driver.close();                             // Stop the ScreenRecorder                            screenRecorder.stop();                            

输出
录制的视频保存在“C:users<<UserName>>Videos”文件夹,如下图所示

C:\Users\Administrator\Videos

8、Selenium网格
http://www.yiibai.com/selenium/selenium_grids.html

转载于:https://www.cnblogs.com/conquerorren/p/8252832.html

【Selenium-WebDriver自学】Selenium测试设计技术(十三)相关推荐

  1. MBIST:用于嵌入式存储器的可测试设计技术

    MBist技术可以自动实现存储器单元或阵列的RTL级内建自测试电路,MBIST的EDA工具支持多种测试算法的自动实现,可针对一个或多个内嵌存储器自动创建BIST逻辑,并完成BIST逻辑与存储器的连接, ...

  2. 减轻产品风险的测试设计技术

    为什么80%的码农都做不了架构师?>>>    ( Erik van Veenendaal是一名国际领先的顾问和培训师,和一名在软件测试和质量管理领域广受认可的专家. 他是Impro ...

  3. Selenium_用selenium webdriver实现selenium RC中的类似的方法

    最近想总结一下学习selenium webdriver的情况,于是就想用selenium webdriver里面的方法来实现selenium RC中操作的一些方法.目前封装了一个ActionDrive ...

  4. 开源应用架构之​Selenium WebDriver(上)

    前不久,InfoQ向大家推荐了几本有关软件架构的新书,引起了国内读者的广泛兴趣.​其中一本是<开源应用架构(The Architecture of Open Source Application ...

  5. 开源应用架构之​Selenium WebDriver

    这几篇文章有些看不懂,不过先存了,再细细品. (上) http://www.infoq.com/cn/news/2011/06/selenium-arch 前不久,InfoQ向大家推荐了几本有关软件架 ...

  6. python爬虫工程师 成长之路八 Selenium WebDriver

    文章目录 Selenium WebDriver 简介 Selenium WebDriver 原理 Selenium WebDriver 安装 Selenium WebDriver 使用 浏览器常用操作 ...

  7. Selenium WebDriver简介

    Selenium WebDriver简介 Selenium WebDriver简介 是Selenium工具箱中功能最强大且最受欢迎的工具之一.WebDriver是Selenium RC的扩展版本,具有 ...

  8. c 后台代码调用ajax,.NET Selenium WebDriver操作调用浏览器后台执行Js(JavaScript)代码...

    1.Selenium WebDriver安装引用 注意:要用使用的浏览器肯定要装,并且Selenium.Chrome.WebDriver版本要和浏览器版一致. 如果要操作其它浏览器,则安装对应其它浏览 ...

  9. Selenium Webdriver概述(转)

    Selenium Webdriver https://www.yiibai.com/selenium/selenium_overview.html# webdriver自动化俗称Selenium 2. ...

最新文章

  1. dbscan算法中 参数的意义_基于变参数的DBSCAN算法
  2. ceph bluestore 源码分析:刷缓存(trim)逻辑
  3. iOS - OC - XML 解析 - NSXMLParser
  4. java f反射_java反射机制[基础学习]
  5. [hiho1159] Poker
  6. 来聊一聊Cookie(小甜饼),及其涉及到的web安全吧
  7. 计算机视觉 - 知识点总结(面试、笔试)
  8. 【2】thinkphp 3.2.3简单介绍
  9. Android笔记(六十七) 自定义控件
  10. Tomcat配置虚拟内存
  11. 中西方对时间的差异_中西方时间观念差异 英文
  12. Hadoop 技术在电信运营商上网日志处理中的应用架构
  13. Java Web 2.1.4 HTML 表单标签与表单设计 (实例)
  14. 当显存不够时是否会调用共享GPU内存?
  15. Python处理图片九宫格,炫酷朋友圈
  16. realize与recognize辨析
  17. 如何定位公众号形象,有什么方法
  18. 虚拟机安装centeros7镜像
  19. 利用Java语言编写一个猜数字游戏(有次数限制)
  20. 工程师排查故障三要诀

热门文章

  1. vue网址路由的实时检测
  2. 190707Python-Redis
  3. 拖动效果,防止选中文字兼容代码
  4. 算法图解学习笔记01:二分查找大O表示法
  5. QT Creator常用快捷键
  6. OpenJ_Bailian——4115鸣人和佐助(带状态的A*)
  7. 开发笔记- iOS监听某些事件的方法简单梳理
  8. 把linux插足到域
  9. winform空间批量控制
  10. Maven提高篇系列之(三)——使用自己的Repository(Nexus)