【Selenium-WebDriver自学】Selenium测试设计技术(十三)
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 error
Logger.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")
@BeforeTest
public 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
【Selenium-WebDriver自学】Selenium测试设计技术(十三)的更多相关文章
- MBIST:用于嵌入式存储器的可测试设计技术
MBist技术可以自动实现存储器单元或阵列的RTL级内建自测试电路,MBIST的EDA工具支持多种测试算法的自动实现,可针对一个或多个内嵌存储器自动创建BIST逻辑,并完成BIST逻辑与存储器的连接, ...
- Selenium WebDriver VS Selenium RC
WebDriver到底是什么? WebDriver是一个Web的自动化测试框架,它支持你执行你的测试用例在不同的浏览器上面,并不像Selenium一样只支持Firefox. WebDriv ...
- Selenium_用selenium webdriver实现selenium RC中的类似的方法
最近想总结一下学习selenium webdriver的情况,于是就想用selenium webdriver里面的方法来实现selenium RC中操作的一些方法.目前封装了一个ActionDrive ...
- Selenium WebDriver 之 PageObjects 模式 by Example
目录 1. 项目配置 2. 一个WebDriver简单例子 3. 使用Page Objects模式 4. 总结 5. Troubleshooting 6. 参考文档 本篇文章通过例子来阐述一下Sele ...
- Selenium Webdriver概述(转)
Selenium Webdriver https://www.yiibai.com/selenium/selenium_overview.html# webdriver自动化俗称Selenium 2. ...
- 【零基础】Selenium:Webdriver图文入门教程java篇(附相关包下载)
一.selenium2.0简述 与一般的浏览器测试框架(爬虫框架)不同,Selenium2.0实际上由两个部分组成Selenium+webdriver,Selenium负责用户指令的解释(code), ...
- Selenium Tutorial (1) - Starting with Selenium WebDriver
Starting with Selenium WebDriver Selenium WebDriver - Introduction & Features How Selenium WebDr ...
- selenium webdriver学习(一)------------快速开始(转载JARVI)
selenium webdriver学习(一)------------快速开始 博客分类: Selenium-webdriver selenium webdriver 学习 selenium webd ...
- Selenium UI自动化测试 Selenium Automatic Testing
https://www.cnblogs.com/sunada2005/archive/2013/12/22/3486314.html UI Automatic Testing 1. 什么样的项目适合自 ...
随机推荐
- ASP.NET AJAX入门系列(4):使用UpdatePanel控件(一)
UpdatePanel可以用来创建丰富的局部更新Web应用程序,它是ASP.NET 2.0 AJAX Extensions中很重要的一个控件,其强大之处在于不用编写任何客户端脚本,只要在一个页面上添加 ...
- DeviceIoControl函数对应的四种数据交换方式
交换方式 输入缓冲区 输出缓冲区 METHOD_BUFFE ...
- Maven下载项目依赖jar包和使用方法
一.Maven3.5.0安装与配置+Eclipse应用 参考:Maven3.5.0安装与配置+Eclipse应用 二.http://mvnrepository.com/ 此处以http://mvnre ...
- Spring Cloud Eureka 服务治理
Spring Cloud Eureka 是 Spring Cloud Netflix 微服务套件的一部分,基于 Netflix Eureka 做了二次封装,主要负责完成微服务架构中的服务治理功能,服务 ...
- java面试题001
1.指针和函数的关系 这里主要谈指针函数和函数指针,在c中指针函数是返回值为指针的函数:函数指针是指向函数的指针变量. 2.什么是事务? 为了完成对数据的操作,要求并发访问在多个构件之间共享的数据.这 ...
- jQuery模态框实现 后台添加删除修改Ip端口
主要用到,$('#i1').each(),标签里绑定函数可传参数this <!DOCTYPE html> <html lang="en"> <head ...
- WebGL和ThreeJs学习5--ThreeJS基本功能控件
Threejs 2017年6月6日 15:06 Stats: new Stats();性能监视器,性能测试的方法,引入 Stats.js http://www.hewebgl.com ...
- Scrapy环境安装
开始安装前,建议安装Visual C++ 2015 Build Tools,否则会一直出现如下提示: 下载地址:http://landinghub.visualstudio.com/visual-cp ...
- Linux环境下查看线程数的几种方法
1.cat /proc/${pid}/status 2.pstree -p ${pid} 3.top -p ${pid} 再按H,或者直接输入 top -bH -d 3 -p ${pid} top ...
- 解决Sublime Text 3中文显示乱码问题
之前用Sublime Text 2,阅读了你是猴子派的救兵吗写的博客解决Sublime Text 2中文显示乱码问题,解决了问题. 后来嫌版本2启动太慢了,换成Sublime Text 3之后,发现网 ...