【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:UsersAdministratorVideos

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

原文地址:https://www.cnblogs.com/conquerorren/p/8252832.html