Tuesday, 4 August 2015

Parallel execution of selenium webdriver test using testng

How to run selenium webdriver test scripts parallel in more two environments using testng suite, testng has a feature by which we can create multiple instance of a single testng class file.

In below example, I created a selenium webdriver test script for google search. Which will run on two browsers firefox and IE.

package com.test;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class GoogleTest {

  private WebDriver driver;
  private String baseUrl;

  @BeforeClass
  @Parameters({ "browsertype"})
  public void setUp(String browsertype) throws Exception {
     if(browsertype.contains("IE")) {
               File IEDriver = new File("IEDriverServer.exe");
               System.setProperty("webdriver.ie.driver", IEDriver.getAbsolutePath() );
               driver = new InternetExplorerDriver();
    }
     else if(browsertype.contains("Firefox")){
                  driver = new FirefoxDriver();
     }      
    baseUrl = "https://www.google.co.in/";
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    driver.manage().window().maximize();
  }

  @Test
  public void testUntitled() throws Exception {
    driver.get(baseUrl + "/");
    driver.findElement(By.id("gbqfq")).clear();
    driver.findElement(By.id("gbqfq")).sendKeys("Testing");
    driver.findElement(By.id("gbqfb")).click();
    driver.findElement(By.id("ab_opt_icon")).click();
    driver.findElement(By.cssSelector("#ab_as > div")).click();
    driver.findElement(By.xpath("//input[@value='Advanced Search']")).click();
  }

  @AfterClass
  public void tearDown() throws Exception {
    driver.quit(); 
  }
}; 

In this test I used dataprovider annotation of testng so need to pass “browsertype” variable from testng suite.xml file.

Here is testng suite.xml file. You should add “parallel="tests” attribute in suite tag, thread-count value more than 2. Add attribute “preserve-order="true” in test tag.

<suite annotations="JDK" name="Scenario1" parallel="tests" thread-count="2" verbose="1">
   
   <test junit="false" name="Scenario1" preserve-order="true">
        <parameter name="browsertype" value="Firefox">
        <classes>
            <class name="com.test.GoogleTest">
        </class></classes>
    </parameter></test>

    <test junit="false" name="Scenario2" preserve-order="true">
        <parameter name="browsertype" value="IE"> 
        <classes>
            <class name="com.test.GoogleTest">
        </class></classes>
    </parameter></test>
</suite>

No comments:

Post a Comment