Module 3 - Selenium WebDriver - Example 1

From Training Material
Revision as of 21:27, 28 May 2013 by Bernard Szlachta (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
package com.shk.webdriver.sanity;

import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

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

  @Before
  public void setUp() throws Exception {
    driver = new FirefoxDriver();
    baseUrl = "http://www.google.co.uk/";
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.MILLISECONDS);
  }

  @Test
  public void testExercise3() throws Exception {
    driver.get(baseUrl);
    driver.findElement(By.id("gbqfq")).clear();
    WebElement  searchUI = driver.findElement(By.id("gbqfq"));
    searchUI.sendKeys("Noble prog ltd");
    searchUI.sendKeys(Keys.ENTER);
    WebDriverWait waitforLink = new WebDriverWait(driver,10);
    waitforLink.until(ExpectedConditions.presenceOfElementLocated(By.linkText("NobleProg - Training Courses and " +
    		"Consultancy | NobleProg")) );
    driver.findElement(By.linkText("NobleProg - Training Courses and Consultancy | NobleProg")).click();
    WebDriverWait wait = new WebDriverWait(driver, 5);
    wait.pollingEvery(10,TimeUnit.MILLISECONDS);
    WebDriverWait waitfor = new WebDriverWait(driver, 5);
    waitfor.pollingEvery(10,TimeUnit.MILLISECONDS);
    assertThat("", is(not(driver.getTitle())));
  }

  @After
  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 String closeAlertAndGetItsText() {
    try {
      Alert alert = driver.switchTo().alert();
      if (acceptNextAlert) {
        alert.accept();
      } else {
        alert.dismiss();
      }
      return alert.getText();
    } finally {
      acceptNextAlert = true;
    }
  }
}