如何使用Webdriver,Java和Junit / TestNG运行多个浏览器实例?

时间:2014-06-06 14:42:45

标签: java junit selenium-webdriver testng

我准备好执行测试,但需要很长时间才能完成。在这个测试中我输入了csv数据,所以基本上整个测试将运行56次。我想知道我是否可以使用多个浏览器实例并将工作负载分成四个实例。它会节省我一些时间。我尝试使用TestNG的ThreadPoolSize,但它并没有按照我的意愿行事。它为四个firefox实例使用相同的数据。我希望每个浏览器都拥有自己独特的数据。请检查我的代码,让我知道我错过了什么。我真的很喜欢每个人的帮助。

public class StudentPageTest {
WebDriver driver;
DesiredCapabilities capability; 
WebElement element;
WebDriverWait wait;
private String baseURL;

@BeforeTest
public void setUp() throws MalformedURLException{
    //capability = DesiredCapabilities.firefox();
    //driver = new FirefoxDriver();
    //wait = new WebDriverWait(driver, 120);
    //driver.manage().deleteAllCookies();
    baseURL = "http://somewebsite.com";

}
@SuppressWarnings("resource")
@Test(threadPoolSize = 4)
public void StudentPortalTest() throws InterruptedException, IOException{
    driver = new FirefoxDriver();
    wait = new WebDriverWait(driver, 120);
    driver.manage().deleteAllCookies();
    String studentId = "studentID.csv";
    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ",";

    br = new BufferedReader(new FileReader(studentId));
    while ((line = br.readLine()) != null) {
        String[] student_id = line.split(cvsSplitBy);

        //Logging in Student Portal---------------------------------------------------------------------------------------------------------------|
        for (int i = 0; i < student_id.length; i++) {       
            driver.get(baseURL+student_id[i]);
            driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
            driver.findElement(By.cssSelector(".logo>img")).isDisplayed();
            driver.findElement(By.cssSelector("#UserName")).sendKeys("SecretUserName");
            driver.findElement(By.cssSelector("#Password")).sendKeys("EvenMoreSecretPassword");
            driver.findElement(By.cssSelector(".submitBtn")).click();
            driver.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);
            Thread.sleep(4000);
           ...............and the test goes on below................... 
    }
@AfterTest
public void tearDown(){
    driver.quit();
    }
 }

3 个答案:

答案 0 :(得分:0)

您可以让Selenium grid执行分发任务。使用TestNG使用dataprovider并行运行您的案例。使用dataprovider读取您的csv并将一个数据传递给一个@Test。 在套件xml中设置dataprovider线程计数,并确保设置@DataProvider(parallel=true)

转到您的代码,将实例化firefoxdriver的调用替换为remotewebdriver以使用网格。确保您的驱动程序不属于班级,但是threadlocalthreadlocal<driver>

答案 1 :(得分:0)

我尝试了许多不同的方法来达到你想要做的同样的事情。经过大量的反复试验后,我终于遇到了一个对我有用的解决方案。

  1. 您需要Selenium Grid然后您可以设置几个节点来运行不同的浏览器

  2. 你需要像你一直使用的TestNG,但不是试图使用线程,而是使用.xml文件将参数传递给你的测试,这将一次又一次地运行一个测试。

  3. 如果您仔细阅读this文档并按照步骤操作,则应该能够获得相同的结果

答案 2 :(得分:0)

@Test(threadPoolSize = 4,invocationCount = 4)