如何在一台计算机上同时使用Selenium在2个浏览器上执行操作?

时间:2015-06-23 10:51:37

标签: java selenium concurrency

我正在使用Selenium和Java进行黑盒测试。我想打开两个浏览器并同时在这些浏览器上执行一些操作(如单击按钮,填充一些文本字段......),以便我可以看到系统将如何响应。我搜索了这个问题,并了解了Selenium Grid。但它似乎在几台机器上运行,而不是一台机器。

我想知道我的问题是否有任何简单的解决方案,我不需要安装任何其他工具。我尝试使用Thread但它没用。

1 个答案:

答案 0 :(得分:0)

我仍然相信使用Threads是可用的最佳解决方案。即使Threads不能并行执行(由JVM或OS决定何时应该运行一个线程),我们可以使用以下代码在线程之间切换。切换将以毫秒为间隔发生,看起来几乎是平行的。

欢迎对可以改进的内容给予反馈。

请找到以下代码:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class App implements Runnable {

    WebDriver driver;
    String threadName;

    public App(String threadName, WebDriver driver) {
        this.threadName = threadName;
        this.driver = driver;
    }

    public void run() {

        if (threadName.equals("one")) {
            System.out.println("one : " + driver.getTitle());
        } else {
            System.out.println(driver.getTitle());
        }

        if (threadName.equals("one")) {
            System.out.println(driver.getTitle());
        } else {
            System.out.println("two : " + driver.getTitle());
        }

        if (threadName.equals("one")) {
            System.out.println("one one one");
        } else {
            System.out.println("two two two");
        }
    }

    public static void main(String[] args) {
        WebDriver driver1 = new FirefoxDriver();
        driver1.get("https://www.google.com");

        WebDriver driver2 = new FirefoxDriver();
        driver2.get("https://en.wikipedia.com");

        ExecutorService executor = Executors.newFixedThreadPool(50);
        executor.execute(new App("one", driver1));
        executor.execute(new App("two", driver2));
    }
}

输出如下所示(由于随机的线程切换,这可能会有所不同)

  一个:谷歌   维基百科,免费的百科全书
  谷歌
  一一一   二:维基百科,免费百科全书
  两两两个

相关问题