[英]Cucumber with Java Selenium framework
我现在是一名手动测试员,最近我转移到 Selenium,在我的公司,现在他们告诉我从头开始为一个项目创建 Cucumber Java Selenium 框架。 我的要求是我需要创建一个类,它包含 selenium 的所有方法,例如 sendKeys、Click、dragAndDrop、mouseHover,就像我需要放在一个类中的所有 selenium 相关操作......我面临着非常困难。
有没有人有这种类型的类,其中包含所有 Selenium 操作?
您可以使用如下所示的 webdriver 方法。 有关完整列表,请查看https://seleniumhq.github.io/selenium/docs/api/rb/method_list.html
get()
getCurrentUrl()
findElement(By, by) and click()
isEnabled()
findElement(By, by) with sendKeys()
findElement(By, by) with getText()
Submit()
findElements(By, by)
你不需要一个包含所有这些动作的类; Selenium 提供了开箱即用的功能。 这可以通过实例化驱动程序的新实例来实现:
WebDriver driver = new ChromeDriver();
然后调用你需要的函数:
driver.getElement(By.id("element")).click();
创建一个新类来包装现有函数是一种可怕的做法。 如果您正在为 Selenium 测试寻找好的设计模式,请查找“页面对象模型”。
希望这些方法对你有帮助
public static void wait(int secs) {
try {
Thread.sleep(1000 * secs);
} catch (InterruptedException e) {
}
}
/**
* Generates the String path to the screenshot taken.
* Within the method, the screenshot is taken and is saved into FileUtils.
* The String return will have a unique name destination of the screenshot itself.
*
* @param name Test name passed in as a String
* @return unique String representation of the file's location / path to file
*/
public static String getScreenshot(String name) {
// name the screenshot with the current date time to avoid duplicate name
//for windows users or if you cannot get a screenshot
String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MMdd_hh_mm_ss_a"));
// TakesScreenshot ---> interface from selenium which takes screenshots
TakesScreenshot ts = (TakesScreenshot) Driver.getDriver();
File source = ts.getScreenshotAs(OutputType.FILE);
// full path to the screenshot location
String target = System.getProperty("user.dir") + "/test-output/Screenshots/" + name + date + ".png";
//if screenshot doesn't work
//try to provide hardcoded path
// String target = "/Users/studio2/IdeaProjects/Spring2019FinalTestNGFramework/screenshots/" + name + date + ".png";
File finalDestination = new File(target);
// save the screenshot to the path given
try {
FileUtils.copyFile(source, finalDestination);
} catch (IOException e) {
e.printStackTrace();
}
return target;
}
/*
* switches to new window by the exact title
* returns to original window if windows with given title not found
*/
public static void switchToWindow(String targetTitle) {
String origin = Driver.getDriver().getWindowHandle();
for (String handle : Driver.getDriver().getWindowHandles()) {
Driver.getDriver().switchTo().window(handle);
if (Driver.getDriver().getTitle().equals(targetTitle)) {
return;
}
}
Driver.getDriver().switchTo().window(origin);
}
public static void hover(WebElement element) {
Actions actions = new Actions(Driver.getDriver());
actions.moveToElement(element).perform();
}
/**
* return a list of string from a list of elements
* text
*
* @param list of webelements
* @return
*/
public static List<String> getElementsText(List<WebElement> list) {
List<String> elemTexts = new ArrayList<>();
for (WebElement el : list) {
if (!el.getText().isEmpty()) {
elemTexts.add(el.getText());
}
}
return elemTexts;
}
/**
* Extracts text from list of elements matching the provided locator into new List<String>
*
* @param locator
* @return list of strings
*/
public static List<String> getElementsText(By locator) {
List<WebElement> elems = Driver.getDriver().findElements(locator);
List<String> elemTexts = new ArrayList<>();
for (WebElement el : elems) {
if (!el.getText().isEmpty()) {
elemTexts.add(el.getText());
}
}
return elemTexts;
}
public static WebElement waitForVisibility(WebElement element, int timeToWaitInSec) {
WebDriverWait wait = new WebDriverWait(Driver.getDriver(), timeToWaitInSec);
return wait.until(ExpectedConditions.visibilityOf(element));
}
public static WebElement waitForVisibility(By locator, int timeout) {
WebDriverWait wait = new WebDriverWait(Driver.getDriver(), timeout);
return wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
}
public static WebElement waitForClickability(WebElement element, int timeout) {
WebDriverWait wait = new WebDriverWait(Driver.getDriver(), timeout);
return wait.until(ExpectedConditions.elementToBeClickable(element));
}
public static WebElement waitForClickability(By locator, int timeout) {
WebDriverWait wait = new WebDriverWait(Driver.getDriver(), timeout);
return wait.until(ExpectedConditions.elementToBeClickable(locator));
}
public static Boolean waitForURL(String actualURL, int timeout) {
WebDriverWait wait = new WebDriverWait(Driver.getDriver(), 5);
return wait.until(ExpectedConditions.urlToBe(actualURL));
}
public static void waitForPageToLoad(long timeOutInSeconds) {
ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");
}
};
try {
Logger logger = Logger.getLogger(UtilsBrowser.class);
logger.info("Waiting for page to load...");
WebDriverWait wait = new WebDriverWait(Driver.getDriver(), timeOutInSeconds);
wait.until(expectation);
} catch (Throwable error) {
System.out.println(
"Timeout waiting for Page Load Request to complete after " + timeOutInSeconds + " seconds");
}
}
public static WebElement fluentWait(final WebElement webElement, int timeinsec) {
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(Driver.getDriver())
.withTimeout(Duration.ofSeconds(timeinsec))
.pollingEvery(Duration.ofMillis(500))
.ignoring(NoSuchElementException.class);
WebElement element = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return webElement;
}
});
return element;
}
/**
* Verifies whether the element matching the provided locator is displayed on page
*
* @param by
* @throws AssertionError if the element matching the provided locator is not found or not displayed
*/
public static void verifyElementDisplayed(By by) {
try {
assertTrue("Element not visible: " + by, Driver.getDriver().findElement(by).isDisplayed());
} catch (NoSuchElementException e) {
e.printStackTrace();
Assert.fail("Element not found: " + by);
}
}
/**
* Verifies whether the element matching the provided locator is NOT displayed on page
*
* @param by
* @throws AssertionError the element matching the provided locator is displayed
*/
public static void verifyElementNotDisplayed(By by) {
try {
Assert.assertFalse("Element should not be visible: " + by, Driver.getDriver().findElement(by).isDisplayed());
} catch (NoSuchElementException e) {
e.printStackTrace();
}
}
/**
* Verifies whether the element is displayed on page
*
* @param element
* @throws AssertionError if the element is not found or not displayed
*/
public static void verifyElementDisplayed(WebElement element) {
try {
assertTrue("Element not visible: " + element, element.isDisplayed());
} catch (NoSuchElementException e) {
e.printStackTrace();
Assert.fail("Element not found: " + element);
}
}
/**
* Waits for element to be not stale
*
* @param element
*/
public void waitForStaleElement(WebElement element) {
int y = 0;
while (y <= 15) {
if (y == 1)
try {
element.isDisplayed();
break;
} catch (StaleElementReferenceException st) {
y++;
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (WebDriverException we) {
y++;
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* Selects a random value from a dropdown list and returns the selected Web Element
*
* @param select
* @return
*/
public static WebElement selectRandomTextFromDropdown(Select select) {
Random random = new Random();
List<WebElement> weblist = select.getOptions();
int optionIndex = 1 + random.nextInt(weblist.size() - 1);
select.selectByIndex(optionIndex);
return select.getFirstSelectedOption();
}
/**
* Clicks on an element using JavaScript
*
* @param element
*/
public void clickWithJS(WebElement element) {
((JavascriptExecutor) Driver.getDriver()).executeScript("arguments[0].scrollIntoView(true);", element);
((JavascriptExecutor) Driver.getDriver()).executeScript("arguments[0].click();", element);
}
/**
* Scrolls down to an element using JavaScript
*
* @param element
*/
public void scrollToElement(WebElement element) {
((JavascriptExecutor) Driver.getDriver()).executeScript("arguments[0].scrollIntoView(true);", element);
}
/**
* Performs double click action on an element
*
* @param element
*/
public void doubleClick(WebElement element) {
new Actions(Driver.getDriver()).doubleClick(element).build().perform();
}
/**
* Changes the HTML attribute of a Web Element to the given value using JavaScript
*
* @param element
* @param attributeName
* @param attributeValue
*/
public void setAttribute(WebElement element, String attributeName, String attributeValue) {
((JavascriptExecutor) Driver.getDriver()).executeScript("arguments[0].setAttribute(arguments[1], arguments[2]);", element, attributeName, attributeValue);
}
public String[] fromListToString(List<WebElement> x) {
String[] trans = new String[x.size()];
for (WebElement xx : x) {
int count = 0;
trans[count] = xx.getText();
count++;
}
Arrays.sort(trans);
return trans;
}
/**
* Highlighs an element by changing its background and border color
*
* @param element
*/
public static void highlight(WebElement element) {
((JavascriptExecutor) Driver.getDriver()).executeScript("arguments[0].setAttribute('style', 'background: yellow; border: 2px solid red;');", element);
wait(1);
((JavascriptExecutor) Driver.getDriver()).executeScript("arguments[0].removeAttribute('style', 'background: yellow; border: 2px solid red;');", element);
}
/**
* Checks or unchecks given checkbox
*
* @param element
* @param check
*/
public static void selectCheckBox(WebElement element, boolean check) {
if (check) {
if (!element.isSelected()) {
element.click();
}
} else {
if (element.isSelected()) {
element.click();
}
}
}
public static void grabHold(WebDriver driver) {
/* /NOTE: Be sure to set -> String parentHandle=driver.getWindowHandle(); prior to the action preceding method deployment */
String parentHandle = driver.getWindowHandle();
Set<String> windows = driver.getWindowHandles();
for (String window : windows) {
if (window != parentHandle)
driver.switchTo().window(window);
}
}
public static void waitUntilTitleEquals(int timeout, String x) {
WebDriverWait wait = new WebDriverWait(Driver.getDriver(), timeout);
wait.until(ExpectedConditions.titleContains(x));
}
public static int getRandomNumInRange(int low, int high) {
Random random = new Random();
return random.nextInt(high - low) + low;
}
public void waitForPresenceOfElementByCss(String css) {
WebDriverWait wait = new WebDriverWait(Driver.getDriver(),
Long.parseLong(ConfigurationReader.getProperties("timeout")));
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(css)));
}
public void hitEnterUsingRobot() {
Robot rb;
try {
rb = new Robot();
rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_ENTER);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public boolean verifyAlertPresent() {
try {
Driver.getDriver().switchTo().alert();
return true;
} catch (NoAlertPresentException Ex) {
// System.out.println("Alert is not presenet");
}
return false;
}
public boolean isElementVisible(By arg0) {
boolean elementVisible = false;
try {
(new WebDriverWait(Driver.getDriver(), 60)).until(ExpectedConditions.visibilityOfElementLocated(arg0));
elementVisible = true;
} catch (TimeoutException ex) {
elementVisible = false;
}
return elementVisible;
}
public static boolean isElementNotVisible(By arg0) {
boolean elementVisible = false;
try {
//these two waitinf for webelement to be gone
// (new WebDriverWait(Driver.getDriver(), 60)).until(ExpectedConditions.invisibilityOfElementLocated(arg0));
(new WebDriverWait(Driver.getDriver(), 60)).until(ExpectedConditions.not(ExpectedConditions.presenceOfAllElementsLocatedBy(arg0)));
elementVisible = true;
} catch (NullPointerException ex) {
elementVisible = false;
}
return elementVisible;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.