65.9K
CodeProject 正在变化。 阅读更多。
Home

重用 Selenium WebDriver 解决方案

2012年11月14日

CPOL

2分钟阅读

viewsIcon

35327

downloadIcon

308

本文档描述了如何在 Selenium 测试崩溃时重用 WebDriver,或者如何在运行时调试 Selenium 脚本。

引言

自从我开始使用 Selenium 以来,已经有一段时间了,但当我开始使用时,主要问题出现了:“为了调试 Selenium 脚本,需要从第一步重新运行脚本”,这真是太无聊了。所以我一直在寻找解决这个问题的方案。从一开始,RMI 就进入了我的脑海。

背景

我的目标是从不同的应用程序获取 WebDriver,以便每次脚本崩溃时,我都能从最后执行的函数开始调试。此外,我还希望能够开发一个小脚本来检查页面,以便找到其中的问题。

我是一名 QTP 开发人员,根据我的经验,我发现“在页面中查找元素”是最常见的问题。但 QTP 除了 Selenium 之外,还有一个很大的优势:它可以从脚本的任何一点开始运行。考虑到这一点,我意识到我需要在 Selenium 中实现 QTP 的这个功能。因此,从 RMI 开始,我创建了两个应用程序:一个带有 WebDriver 的服务器和一个带有 Selenium 脚本的客户端。服务器将在测试脚本开发过程中持有 WebDriver。

代码是在 Eclipse Juno 中使用 JRE 7 编写的。我使用 Maven 加载所需的库。如果您不熟悉 RMI,请在继续之前考虑以下资源:http://yama-linux.cc.kagoshima-u.ac.jp/~yamanoue/researches/java/rmi-ex2/

在开始运行解决方案之前,请安装 Maven 插件,这里有一个很好的教程:http://www.metadatatechnology.com/getting-started-with-the-fusion-components/installing-and-configuring-maven/

要以调试模式运行,请启动服务器:WebDriverWrapper 具有 main 函数实现,因此您可以将其作为 Java 应用程序运行。

服务器。

RMI 接口

public interface ReceiveMessageInterface extends Remote
{
 void startup(String x) throws RemoteException; 
 public void close() throws RemoteException;
 public WebElement findElement(By arg0)  throws RemoteException;
 public List<WebElement> findElements(By arg0)  throws RemoteException;
 public void get(String arg0)  throws RemoteException;
 public String getCurrentUrl()  throws RemoteException;
 public String getPageSource()  throws RemoteException;
 public String getTitle()  throws RemoteException;
 public String getWindowHandle()  throws RemoteException;
 public Set<String> getWindowHandles()  throws RemoteException;
 public Options manage()  throws RemoteException;
 public Navigation navigate()  throws RemoteException;
 public void quit()  throws RemoteException;
 public TargetLocator switchTo()  throws RemoteException; 
}

这是 WebDriverWrapper 构造函数

private WebDriverWrapper () throws RemoteException
{
 try{
  // get the address of this host.
  thisAddress= (InetAddress.getLocalHost()).toString();
 }
 catch(Exception e){
  throw new RemoteException("can't get inet address.");
 }
 thisPort=3232;  // this port(registry?fs port)
 System.out.println("this address="+thisAddress+",port="+thisPort);
 try{
 // create the registry and bind the name and object.
 registry = LocateRegistry.createRegistry( thisPort );
  registry.rebind("rmiServer", this); 
 }
 catch(RemoteException e){
 throw e;
 }
}

...此脚本所做的只是通过 ReceiveMessageInterface 将 WebDriverWrapper 放入 JVM 注册表中。

客户端。

在“实际测试”中,您可以使用 WebDriver 接口进行测试

WebDriver driver = FirefoxDriver();

在调试模式下,将上述行更改为以下内容

ReceiveMessageInterface driver = DriverFactory.getDriver();

在客户端,我们从服务器获取加载的驱动程序,并通过 ReceiveMessageInterface 使用它。

DriverFactory.getDriver() 方法在本例中是一个伪工厂函数。

图表

附加说明

对于每个 WebDriver 功能,您需要更新 RemoteMessageInterface 并实现 Wrapper 类中的方法,以便在脚本中使用它。

历史

版本 2

© . All rights reserved.