Friday, November 11, 2016

Exporting selenium IDE tests to WebDriver

Script created in Selenium IDE can be exported to WebDriver/Remote Control in the languages java/c#/python/ruby that can be run using junit(java), RSpec(ruby), nUnit and testNG. 


To export test in TestNG with selenium webdriver, follow below steps:

  • Record the required operations on the application.
  • Go to File>Export Test Case as Java / TestNG / WebDriver (can export test script in different formats)
Exporting test in Selenium IDE

  • Export the test.
  • A java file will be created with content as shown below


package com.example.tests;

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.testng.annotations.*;
import static org.testng.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class TESTINGAA {
  private WebDriver driver;
  private String baseUrl;
  private boolean acceptNextAlert = true;
  private StringBuffer verificationErrors = new StringBuffer();

  @BeforeClass(alwaysRun = true)
  public void setUp() throws Exception {
    driver = new FirefoxDriver();
    baseUrl = "https://www.google.co.in/";
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  }

  @Test
  public void testINGAA() throws Exception {
    driver.get(baseUrl + "/?gfe_rd=cr&ei=_OMdWJKzEO3I8AeAqrBg&gws_rd=ssl");
    driver.findElement(By.id("lst-ib")).clear();
    driver.findElement(By.id("lst-ib")).sendKeys("TESTING AUTOMATION CONEPTS");
    assertTrue(isElementPresent(By.linkText("TESTING AUTOMATION CONCEPTS")));
    driver.findElement(By.linkText("TESTING AUTOMATION CONCEPTS")).click();
    driver.findElement(By.linkText("Test automation - Wikipedia")).click();
    assertTrue(isElementPresent(By.linkText("Test automation - Wikipedia")));
  }

  @AfterClass(alwaysRun = true)
  public void tearDown() throws Exception {
    driver.quit();
    String verificationErrorString = verificationErrors.toString();
    if (!"".equals(verificationErrorString)) {
      fail(verificationErrorString);
    }
  }

  private boolean isElementPresent(By by) {
    try {
      driver.findElement(by);
      return true;
    } catch (NoSuchElementException e) {
      return false;
    }
  }

  private boolean isAlertPresent() {
    try {
      driver.switchTo().alert();
      return true;
    } catch (NoAlertPresentException e) {
      return false;
    }
  }

  private String closeAlertAndGetItsText() {
    try {
      Alert alert = driver.switchTo().alert();
      String alertText = alert.getText();
      if (acceptNextAlert) {
        alert.accept();
      } else {
        alert.dismiss();
      }
      return alertText;
    } finally {
      acceptNextAlert = true;
    }
  }
}

No comments:

Post a Comment