如何在Selenium中使用已经打开的firefox进行测试

这个宣言

WebDriver driver = new FirefoxDriver(); 

总是打开Firefox的新实例窗口。 它不使用已经打开的Firefox。

任何人都可以让我知道如何使用已经打开的Firefox进行测试而不是打开一个新的?

要小心,因为如果驱动程序崩溃了一次,那么之后必须执行的所有测试用例都会受到影响,因为他们使用相同的驱动程序,你也将共享cookie,也许会话已经打开过,等等

更强大的解决方案是为每个测试用例创建一个新的WebDriver,因为这样做可以减少所有测试用例对其他测试用例的依赖。

如果激励你的原因是每个WebDriver创建的时间,也许你可以开始考虑并行运行测试用例,例如使用TestNG。

谢谢

像这样使用远程Web驱动程序。

 System.Uri uri = new System.Uri("http://localhost:7055/hub"); WebDriver = new RemoteWebDriver(uri, DesiredCapabilities.Firefox()); 

它将使用已经打开的Firefox浏览器。 您可以在此博客文章中查看此方法的详细信息。

http://www.binaryclips.com/2016/03/selenium-web-driver-in-c-how-to.html

在进行测试时,您应该只将您的webdriver实例化一次,然后将其作为构造函数中其他类的参数传递。 像这样的东西:

 public class Test { WebDriver driver = new FirefoxDriver(); @Test public void testHomePage() { HomePage hp = new HomePage(driver); //code here } } public class HomePage{ private static WebDriver driver; public HomePage(WebDriver driver) { this.driver = driver;} } 

在Java中,当您说new的对象被实例化时。 对于WebDriver,每个new都是一个新的浏览器窗口。

如果要使用相同的浏览器,请使用相同的driver对象。

 driver.get("URL PATH"); 

这将通过已打开的浏览器转到新的Url。

Java示例。 首先,您需要运行Selenium服务器。

 java -jar C:\selenium-server-standalone-2.53.0.jar 

要开始新会话(第一个脚本):

 WebDriver driver = new RemoteWebDriver( new URL("http://localhost:4444/wd/hub"), DesiredCapabilities.firefox()); 

然后,重用(附加)该会话(第二个脚本):

 WebDriver driver = new RemoteWebDriver( new URL("http://localhost:7055/hub"), DesiredCapabilities.firefox()); 

注意不同的端口号。

最好的方法是,扩展RemoteWebDriver并覆盖startSession方法 – :

脚步:

  1. 使用command-java -jar selenium-server-standalone-3.xxjar启动selenium服务器。 默认情况下,您的会话从端口4444开始。

  2. 打开urlhttp:// localhost:4444 / wd / hub / static / resource / hub.html

  3. 启动新的firefox会话点击创建会话按钮并选择firefox浏览器。

  4. 会话开始后,复制会话ID并将其粘贴到您想要的属性文件或xml文件中。

  5. 读取会话ID形成您在以下方法中保存的文件

     @Override protected void startSession(Capabilities desiredCapabilities) { String sid = getSessionIDFromPropertyFile(); if (sid != null) { setSessionId(sid); try { getCurrentUrl(); } catch (WebDriverException e) { // session is not valid sid = null; } } if (sid == null) { super.startSession(desiredCapabilities); saveSessionIdToSomeStorage(getSessionId().toString()); } }