Java tutorial
package com.davidgaskins.learningtounittest; import static com.davidgaskins.learningtounittest.MoneyMaker.timeToWait; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; /* * Copyright 2014. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.davidgaskins.com/license * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * * @author David Gaskins <david.s.gaskins@gmail.com> * */ public class Utilities { public static class MoreElementsThanExpectedException extends Exception { private static final long serialVersionUID = 0; } public static void validateCorrectSize(List l) throws MoreElementsThanExpectedException { if (l.size() > 1) { throw new MoreElementsThanExpectedException(); } } /** * Have the system wait for a specified amount of seconds * @param delayInSeconds */ public static void tryToWait(double delayInSeconds) { try { final int milliSecondsInSeconds = 1000; Thread.sleep((long) (delayInSeconds * milliSecondsInSeconds)); } catch (InterruptedException ie) { cleanUpSystem(ie); } } /** * * Print an exception and have the system leave * @param e */ public static void cleanUpSystem(Exception e) { e.printStackTrace(); System.exit(-1); } public static WebElement getElement(WebDriver driver, String path) { WebElement result = null; try { List<WebElement> inputs = driver.findElements(By.xpath(path)); validateCorrectSize(inputs); result = inputs.get(0); } catch (MoreElementsThanExpectedException me) { cleanUpSystem(me); } return result; } public static void clickButton(WebDriver driver, String path) { WebElement element = getElement(driver, path); element.click(); tryToWait(timeToWait); } public static void inputString(WebDriver driver, String pathToElement, String input) { WebElement element = getElement(driver, pathToElement); element.sendKeys(input); tryToWait(timeToWait); } }