NỘI DUNG BÀI HỌC
Các bạn tạo 1 class để làm keyword ví dụ WebUI thì cần khai báo driver trước nhé. Vì chúng ta đang tuân theo mô hình Page Object Model.
private static WebDriver driver;
public WebUI(WebDriver driver) {
WebUI.driver = driver;
}
Các biến giá trị thời gian thiết lập mặc định
private static int TIMEOUT = 10;
private static double STEP_TIME = 0.5;
private static int PAGE_LOAD_TIMEOUT = 20;
Tất cả các hàm trong keyword cần có trạng thái là static để lấy tên class chấm gọi chứ không cần phải khởi tạo đối tượng trang
Các hàm chờ đợi Element để thao tác cho ổn định
//Wait for Element
public static void waitForElementVisible(By by) {
try {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(TIMEOUT), Duration.ofMillis(500));
wait.until(ExpectedConditions.visibilityOfElementLocated(by));
} catch (Throwable error) {
logConsole("Timeout waiting for the element Visible. " + by.toString());
Assert.fail("Timeout waiting for the element Visible. " + by.toString());
}
}
public static void waitForElementVisible(By by, int timeOut) {
try {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeOut), Duration.ofMillis(500));
wait.until(ExpectedConditions.visibilityOfElementLocated(by));
} catch (Throwable error) {
logConsole("Timeout waiting for the element Visible. " + by.toString());
Assert.fail("Timeout waiting for the element Visible. " + by.toString());
}
}
public static void waitForElementPresent(By by) {
try {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(TIMEOUT), Duration.ofMillis(500));
wait.until(ExpectedConditions.presenceOfElementLocated(by));
} catch (Throwable error) {
logConsole("Element not exist. " + by.toString());
Assert.fail("Element not exist. " + by.toString());
}
}
public static void waitForElementPresent(By by, int timeOut) {
try {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeOut), Duration.ofMillis(500));
wait.until(ExpectedConditions.presenceOfElementLocated(by));
} catch (Throwable error) {
logConsole("Element not exist. " + by.toString());
Assert.fail("Element not exist. " + by.toString());
}
}
public static void waitForElementClickable(By by) {
try {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(TIMEOUT), Duration.ofMillis(500));
wait.until(ExpectedConditions.elementToBeClickable(getWebElement(by)));
} catch (Throwable error) {
logConsole("Timeout waiting for the element ready to click. " + by.toString());
Assert.fail("Timeout waiting for the element ready to click. " + by.toString());
}
}
public static void waitForElementClickable(By by, int timeOut) {
try {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeOut), Duration.ofMillis(500));
wait.until(ExpectedConditions.elementToBeClickable(getWebElement(by)));
} catch (Throwable error) {
logConsole("Timeout waiting for the element ready to click. " + by.toString());
Assert.fail("Timeout waiting for the element ready to click. " + by.toString());
}
}
Chờ đợi Trang load xong mới thao tác
//Chờ đợi trang load xong mới thao tác
public void waitForPageLoaded() {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30), Duration.ofMillis(500));
JavascriptExecutor js = (JavascriptExecutor) driver;
//Wait for Javascript to load
ExpectedCondition < Boolean > jsLoad = new ExpectedCondition < Boolean > () {
@Override
public Boolean apply(WebDriver driver) {
return js.executeScript("return document.readyState").toString().equals("complete");
}
};
//Check JS is Ready
boolean jsReady = js.executeScript("return document.readyState").toString().equals("complete");
//Wait Javascript until it is Ready!
if (!jsReady) {
//System.out.println("Javascript is NOT Ready.");
//Wait for Javascript to load
try {
wait.until(jsLoad);
} catch (Throwable error) {
error.printStackTrace();
Assert.fail("FAILED. Timeout waiting for page load.");
}
}
}
Các hàm xử lý cơ bản
public static void sleep(double second) {
try {
Thread.sleep((long)(1000 * second));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public static void logConsole(Object message) {
System.out.println(message);
}
public static WebElement getWebElement(By by) {
return driver.findElement(by);
}
public static List<WebElement> getWebElements(By by) {
return driver.findElements(by);
}
/**
* Verify if a web element is present (findElements.size > 0).
*
* @param by Represent a web element as the By object
* @return true/false
*/
@Step("Check element exist {0}")
public static boolean checkElementExist(By by) {
boolean result = false;
List<WebElement> elementList = getWebElements(by);
if (elementList.size() > 0) {
System.out.println("✅ Element " + by + " existing.");
result = true;
} else {
System.out.println("❌ Element " + by + " NOT exists.");
result = false;
}
return result;
}
// Hàm kiểm tra sự tồn tại của phần tử với lặp lại nhiều lần dùng FluentWait
@Step("Check element exist {0} with retry {1} times and wait time {2} ms")
public static boolean checkElementExist(By by, int maxRetries, int waitTimeMillis) {
System.out.println("Kiểm tra tồn tại phần tử với retry: " + by);
long totalTimeoutMillis = (long) maxRetries * waitTimeMillis;
try {
// FluentWait tương tự như vòng lặp của bạn nhưng hiệu quả hơn,
// không block thread của hệ thống bằng Thread.sleep().
Wait<WebDriver> wait = new FluentWait<>(DriverManager.getDriver())
.withTimeout(Duration.ofMillis(totalTimeoutMillis)) // Tổng thời gian chờ tối đa
.pollingEvery(Duration.ofMillis(waitTimeMillis)) // Tần suất lặp lại (Polling)
.ignoring(NoSuchElementException.class) // Tiếp tục lặp nếu không tìm thấy element
.ignoring(StaleElementReferenceException.class); // Tiếp tục lặp nếu element bị thay đổi
WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(by));
if (element != null) {
System.out.println("✅ Tồn tại phần tử: " + by);
return true;
}
} catch (TimeoutException e) {
System.out.println("❌ Không tìm thấy phần tử sau " + maxRetries + " lần thử.");
return false;
}
return false;
}
public static void openURL(String url) {
driver.get(url);
sleep(STEP_TIME);
logConsole("Open URL: " + url);
}
public static void clickElement(By by) {
waitForElementClickable(by);
sleep(STEP_TIME);
getWebElement(by).click();
logConsole("Click on element " + by);
}
public static void clickElement(By by, int timeout) {
waitForElementClickable(by, timeout);
sleep(STEP_TIME);
getWebElement(by).click();
logConsole("Click on element " + by);
}
public static void setText(By by, String value) {
waitForElementVisible(by);
sleep(STEP_TIME);
getWebElement(by).sendKeys(value);
logConsole("Set text " + value + " on element " + by);
}
public static String getElementText(By by) {
waitForElementVisible(by);
sleep(STEP_TIME);
logConsole("Get text of element " + by);
String text = getWebElement(by).getText();
logConsole("==> TEXT: " + text);
return text; //Trả về một giá trị kiểu String
}
public static String getElementAttribute(By by, String attributeName) {
waitForElementVisible(by);
System.out.println("Get attribute of element " + by);
String value = getWebElement(by).getAttribute(attributeName);
System.out.println("==> Attribute value: " + value);
return value;
}
public static String getElementCssValue(By by, String cssPropertyName) {
waitForElementVisible(by);
System.out.println("Get CSS value " + cssPropertyName + " of element " + by);
String value = getWebElement(by).getCssValue(cssPropertyName);
System.out.println("==> CSS value: " + value);
return value;
}
