Web Design

Selenium Webdriver tips

Selenium Webdriver is an automated testing platform for web pages.  It may not be the easiest or the most user-friendly, and it definitely requires a lot of coding, but it's the most powerful and works with any website.  Even better, it "drives" a real web browser and simulates real clicks, so you're getting a real UI test, not just a URL test.  

It's good stuff, but it's also arcane.  That's why I'm putting together this handy cheat sheet.  Expect it to change over time.

Note: Webdriver supports many languages; my syntax is all for java.  Don't ask me why.

TASK CODE
Start a new web driver, set window size & position

WebDriver driver = new FirefoxDriver();
driver.manage().window().setSize(new Dimension(1024,768));
driver.manage().window().setPosition(new Point(800,0));
driver.get(domain);

Make sure an element has loaded before you target it (implicit wait)
WebElement uname = (new WebDriverWait(driver, 60))
.until(ExpectedConditions.presenceOfElementLocated(By.id("edit-name")));
uname.sendKeys(username);
Make the script wait (explicit wait) Thread.sleep(500);
Close the window when you're done driver.quit();
Take a screenshot
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(scrFile, new File(screenshot + ".png"));
} catch (IOException e) {
// Auto-generated catch block
e.printStackTrace();
}
Click on a web element driver.findElement(By.linkText("EDIT")).click();
Select from a dropdown menu new Select(driver.findElement(By.id("edit-status"))).selectByVisibleText("No");
Make sure something is selected Assert.assertTrue(driver.findElement(By.id("edit-status-0")).isSelected());
Make sure text is present on a page
String body = driver.findElement(By.tagName("body")).getText();
Assert.assertTrue(body.contains(constant.targetuser));
Send report to console System.out.println("Turnover note found");
 
Find an element using xpath driver.findElement(By.xpath("//a[@class='username']"));