Commit 88dec7f8 authored by Đỗ Gia Hưng's avatar Đỗ Gia Hưng

Bai17POM: Refactor toan bo he thong sang Page Object Model

parent 63ae3933
package com.automation.pages;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
/**
* AlertDemoPage - Đại diện cho trang demo Alert tại the-internet.herokuapp.com
* Dùng cho: Bài 11 (Alert, Confirm, Prompt)
*/
public class AlertDemoPage {
private WebDriver driver;
private WebDriverWait wait;
// --- Locators ---
private By btnSimpleAlert = By.xpath("//button[text()='Click for JS Alert']");
private By btnConfirmAlert = By.xpath("//button[text()='Click for JS Confirm']");
private By btnPromptAlert = By.xpath("//button[text()='Click for JS Prompt']");
private By resultText = By.id("result");
public AlertDemoPage(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
public void open() {
System.out.println("[Page]: Mở trang Alert Demo");
driver.get("https://the-internet.herokuapp.com/javascript_alerts");
}
// --- Simple Alert ---
public String triggerSimpleAlertAndAccept() {
System.out.println("[Page]: Click nút Simple Alert");
WebElement btn = driver.findElement(btnSimpleAlert);
highlightElement(btn);
btn.click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String msg = alert.getText();
System.out.println("[Page]: Nội dung Alert: '" + msg + "' → Accept");
alert.accept();
return msg;
}
// --- Confirm Alert ---
public String triggerConfirmAlertAndDismiss() {
System.out.println("[Page]: Click nút Confirm Alert");
WebElement btn = driver.findElement(btnConfirmAlert);
highlightElement(btn);
btn.click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String msg = alert.getText();
System.out.println("[Page]: Nội dung Confirm Alert: '" + msg + "' → Dismiss (Cancel)");
alert.dismiss();
return msg;
}
public String getResultText() {
WebElement result = wait.until(ExpectedConditions.visibilityOfElementLocated(resultText));
highlightElement(result);
return result.getText();
}
// --- Prompt Alert ---
public String triggerPromptAlertSendKeysAndAccept(String inputText) {
System.out.println("[Page]: Click nút Prompt Alert");
WebElement btn = driver.findElement(btnPromptAlert);
highlightElement(btn);
btn.click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
System.out.println("[Page]: Đang nhập '" + inputText + "' vào Prompt Alert");
alert.sendKeys(inputText);
alert.accept();
return inputText;
}
private void highlightElement(WebElement element) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('style', 'border: 3px solid red; background: yellow;');", element);
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
}
}
package com.automation.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
/**
* AnhTesterPage - Đại diện cho trang chủ anhtester.com
* Dùng cho: Bài 7 (Navigate), Bài 14 (JS Scroll), Bài 13 (Actions Hover)
*/
public class AnhTesterPage {
private WebDriver driver;
private WebDriverWait wait;
private Actions actions;
// --- Locators ---
private By menuCourses = By.xpath("//a[contains(., 'Khoá học')]");
private By menuWebsiteTesting = By.xpath("//a[contains(., 'Website Testing')]");
public AnhTesterPage(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver, Duration.ofSeconds(10));
this.actions = new Actions(driver);
}
public void open() {
System.out.println("[Page]: Mở trang anhtester.com");
driver.get("https://anhtester.com");
}
public String getTitle() {
return driver.getTitle();
}
public String getCurrentUrl() {
return driver.getCurrentUrl();
}
public void hoverMenuCourses() {
System.out.println("[Page]: Di chuột (Hover) vào menu 'Khoá học'");
WebElement menu = wait.until(ExpectedConditions.visibilityOfElementLocated(menuCourses));
highlightElement(menu);
actions.moveToElement(menu).perform();
}
public boolean isMenuWebsiteTestingDisplayed() {
System.out.println("[Page]: Kiểm tra menu con 'Website Testing' hiện ra chưa");
WebElement subMenu = wait.until(ExpectedConditions.visibilityOfElementLocated(menuWebsiteTesting));
highlightElement(subMenu);
return subMenu.isDisplayed();
}
public void scrollToBottom() {
System.out.println("[Page]: Cuộn xuống đến cuối trang");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
}
public void scrollUp(int pixels) {
System.out.println("[Page]: Cuộn lên " + pixels + " pixels");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0, -" + pixels + ")");
}
private void highlightElement(WebElement element) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('style', 'border: 3px solid red; background: yellow;');", element);
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
}
}
package com.automation.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
/**
* CmsLoginPage - Đại diện cho trang đăng nhập hệ thống CMS: cms.anhtester.com/login
* Dùng cho: Bài 9 (WebElement Commands), Bài 14 (JS Executor)
*/
public class CmsLoginPage {
private WebDriver driver;
private WebDriverWait wait;
// --- Locators ---
private By emailInput = By.id("email");
private By passwordInput = By.id("password");
private By loginButton = By.xpath("//button[@type='submit']");
public CmsLoginPage(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
public void open() {
System.out.println("[Page]: Mở trang CMS Login: cms.anhtester.com/login");
driver.get("https://cms.anhtester.com/login");
}
public WebElement getEmailInput() {
WebElement el = wait.until(ExpectedConditions.visibilityOfElementLocated(emailInput));
highlightElement(el);
return el;
}
public WebElement getPasswordInput() {
WebElement el = driver.findElement(passwordInput);
highlightElement(el);
return el;
}
public WebElement getLoginButton() {
WebElement el = wait.until(ExpectedConditions.elementToBeClickable(loginButton));
highlightElement(el);
return el;
}
public void enterEmail(String email) {
System.out.println("[Page]: Nhập Email: " + email);
WebElement el = getEmailInput();
el.clear();
el.sendKeys(email);
}
public void enterPassword(String password) {
System.out.println("[Page]: Nhập Password");
WebElement el = getPasswordInput();
el.clear();
el.sendKeys(password);
}
public void clickLogin() {
System.out.println("[Page]: Click nút Login (Selenium click)");
getLoginButton().click();
}
public void clickLoginWithJS() {
System.out.println("[Page]: Click nút Login bằng JavaScript");
WebElement btn = getLoginButton();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", btn);
}
// JS Executor: Gán giá trị trực tiếp vào trường không thể type bình thường
public void setEmailByJS(String email) {
System.out.println("[Page]: Gán Email bằng JS: " + email);
WebElement el = getEmailInput();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].value = '" + email + "';", el);
}
public String getEmailValueByJS() {
WebElement el = driver.findElement(emailInput);
JavascriptExecutor js = (JavascriptExecutor) driver;
return (String) js.executeScript("return arguments[0].value;", el);
}
public String getCurrentUrl() {
return driver.getCurrentUrl();
}
private void highlightElement(WebElement element) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('style', 'border: 3px solid red; background: yellow;');", element);
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
}
}
package com.automation.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
/**
* ContextMenuDemoPage - Trang demo Right Click và Double Click
* Dùng cho: Bài 13 Actions (Right Click, Double Click)
*/
public class ContextMenuDemoPage {
private WebDriver driver;
private WebDriverWait wait;
private Actions actions;
private By rightClickArea = By.xpath("//span[contains(text(),'right click me')]");
private By copyMenuItem = By.xpath("//span[contains(text(),'Copy')]");
private By doubleClickBtn = By.xpath("//button[contains(text(),'Double-Click Me To See Alert')]");
public ContextMenuDemoPage(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver, Duration.ofSeconds(10));
this.actions = new Actions(driver);
}
public void open() {
System.out.println("[Page]: Mở trang Context Menu Demo");
driver.get("https://demo.guru99.com/test/simple_context_menu.html");
}
public void rightClickOnArea() {
System.out.println("[Page]: Thực hiện Right Click");
WebElement area = driver.findElement(rightClickArea);
highlightElement(area);
actions.contextClick(area).perform();
}
public boolean isCopyMenuItemDisplayed() {
WebElement copy = wait.until(ExpectedConditions.visibilityOfElementLocated(copyMenuItem));
return copy.isDisplayed();
}
public void dismissContextMenu() {
actions.sendKeys(Keys.ESCAPE).perform();
}
public void doubleClickButton() {
System.out.println("[Page]: Thực hiện Double Click");
WebElement btn = driver.findElement(doubleClickBtn);
highlightElement(btn);
actions.doubleClick(btn).perform();
}
public void acceptAlertAfterDoubleClick() {
wait.until(ExpectedConditions.alertIsPresent()).accept();
}
private void highlightElement(WebElement element) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('style', 'border: 3px solid red; background: yellow;');", element);
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
}
}
package com.automation.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
public class CustomerPage {
private WebDriver driver;
private WebDriverWait wait;
// --- 1. Locators ---
private By btnAddNewCustomer = By.xpath("//a[contains(@class,'btn-primary') and contains(.,'New Customer')]");
private By inputCompany = By.id("company");
private By inputVat = By.id("vat");
private By inputPhone = By.id("phonenumber");
private By inputWebsite = By.id("website");
private By btnSave = By.xpath("//button[contains(@class,'only-save')]");
// Locators cho việc kiểm tra thành công
private By headerProfileName = By.xpath("//h4[contains(normalize-space(), '')]"); // Sẽ dùng dynamic xpath
private By inputSearch = By.cssSelector("#clients_filter input");
private By firstRowCompanyName = By.xpath("//table[@id='clients']//tbody/tr[1]/td[3]/a");
public CustomerPage(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver, Duration.ofSeconds(15));
}
// --- 2. Actions ---
public void clickNewCustomer() {
System.out.println("[Customer]: Click nút 'New Customer'");
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(btnAddNewCustomer));
highlightElement(element);
element.click();
}
public void enterCustomerInfo(String company, String vat, String phone, String website) {
System.out.println("[Customer]: Điền thông tin khách hàng: " + company);
WebElement comp = wait.until(ExpectedConditions.visibilityOfElementLocated(inputCompany));
highlightElement(comp);
comp.sendKeys(company);
driver.findElement(inputVat).sendKeys(vat);
driver.findElement(inputPhone).sendKeys(phone);
driver.findElement(inputWebsite).sendKeys(website);
}
public void clickSave() {
System.out.println("[Customer]: Click nút 'Save'");
WebElement element = driver.findElement(btnSave);
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
highlightElement(element);
element.click();
}
public String getHeaderProfileName() {
System.out.println("[Customer]: Lấy tên trên Header Profile...");
wait.until(ExpectedConditions.urlContains("/client/"));
// Dynamic xpath để tìm h4 bất kỳ chứa dấu # (thường là định danh khách hàng)
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//h4[contains(normalize-space(), '#')]")));
highlightElement(element);
return element.getText();
}
public boolean isCustomerDisplayedInTable(String companyName) {
System.out.println("[Customer]: Kiểm tra khách hàng trong danh sách: " + companyName);
WebElement search = wait.until(ExpectedConditions.visibilityOfElementLocated(inputSearch));
highlightElement(search);
search.clear();
search.sendKeys(companyName + Keys.ENTER);
try {
By dynamicRow = By.xpath("//table[@id='clients']//tbody//a[normalize-space()='" + companyName + "']");
WebElement result = wait.until(ExpectedConditions.visibilityOfElementLocated(dynamicRow));
highlightElement(result);
return true;
} catch (Exception e) {
return false;
}
}
private void highlightElement(WebElement element) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('style', 'border: 3px solid red; background: yellow;');", element);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.automation.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
/**
* DashboardPage đại diện cho trang chủ quản trị.
* Chứa các thành phần chung như Menu, Header, User Profile...
*/
public class DashboardPage {
private WebDriver driver;
private WebDriverWait wait;
// --- 1. Locators ---
private By menuCustomers = By.xpath("//span[contains(text(),'Customers')]");
private By menuProjects = By.xpath("//span[contains(text(),'Projects')]");
private By menuTasks = By.xpath("//span[contains(text(),'Tasks')]");
public DashboardPage(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
// --- 2. Actions ---
public void openCustomersMenu() {
System.out.println("[Dashboard]: Mở menu Customers");
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(menuCustomers));
highlightElement(element);
element.click();
}
public void openProjectsMenu() {
System.out.println("[Dashboard]: Mở menu Projects");
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(menuProjects));
highlightElement(element);
element.click();
}
/**
* Hàm Highlight nội bộ
*/
private void highlightElement(WebElement element) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('style', 'border: 3px solid red; background: yellow;');", element);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.automation.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
/**
* DragDropDemoPage - Trang demo Drag and Drop
* Dùng cho: Bài 13 Actions (Drag & Drop)
*/
public class DragDropDemoPage {
private WebDriver driver;
private WebDriverWait wait;
private Actions actions;
private By sourceItem = By.xpath("//li[@id='fourth']//a[contains(text(),'5000')]");
private By targetSlot = By.xpath("//ol[@id='amt7']//li[@class='placeholder']");
private By resultItem = By.xpath("//ol[@id='amt7']//li[contains(text(),'5000')]");
public DragDropDemoPage(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver, Duration.ofSeconds(10));
this.actions = new Actions(driver);
}
public void open() {
System.out.println("[Page]: Mở trang Drag & Drop Demo");
driver.get("https://demo.guru99.com/test/drag_drop.html");
}
public void dragAndDropItem() {
System.out.println("[Page]: Tìm và highlight phần tử NGUỒN '5000'");
WebElement source = driver.findElement(sourceItem);
highlightElement(source);
System.out.println("[Page]: Tìm và highlight phần tử ĐÍCH");
WebElement target = driver.findElement(targetSlot);
highlightElement(target);
System.out.println("[Page]: Thực hiện KÉO và THẢ");
actions.dragAndDrop(source, target).perform();
}
public boolean isResultDisplayed() {
WebElement result = wait.until(ExpectedConditions.visibilityOfElementLocated(resultItem));
highlightElement(result);
return result.isDisplayed();
}
private void highlightElement(WebElement element) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('style', 'border: 3px solid red; background: yellow;');", element);
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
}
}
package com.automation.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
/**
* DynamicLoadingPage - Đại diện cho trang Dynamic Loading demo
* Dùng cho: Bài 15 (Explicit Wait, Fluent Wait)
*/
public class DynamicLoadingPage {
private WebDriver driver;
private WebDriverWait wait;
// --- Locators ---
private By startBtn = By.xpath("//button[text()='Start']");
private By loadingSpinner = By.id("loading");
private By finishText1 = By.id("finish");
private By finishText2 = By.xpath("//div[@id='finish']/h4");
public DynamicLoadingPage(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver, Duration.ofSeconds(15));
}
public void openExample1() {
System.out.println("[Page]: Mở trang Dynamic Loading - Ví dụ 1 (Spinner)");
driver.get("https://the-internet.herokuapp.com/dynamic_loading/1");
}
public void openExample2() {
System.out.println("[Page]: Mở trang Dynamic Loading - Ví dụ 2 (Element chưa có trong DOM)");
driver.get("https://the-internet.herokuapp.com/dynamic_loading/2");
}
public void clickStart() {
System.out.println("[Page]: Click nút Start");
WebElement btn = driver.findElement(startBtn);
highlightElement(btn);
btn.click();
}
/**
* Explicit Wait: Chờ Loading Spinner biến mất
*/
public String waitForSpinnerAndGetResult() {
System.out.println("[Page]: Đang dùng Explicit Wait chờ Spinner biến mất...");
wait.until(ExpectedConditions.invisibilityOfElementLocated(loadingSpinner));
System.out.println("[Page]: Spinner đã biến mất! Lấy kết quả...");
WebElement result = driver.findElement(finishText1);
highlightElement(result);
return result.getText();
}
/**
* Fluent Wait: Tìm element xuất hiện bất kỳ lúc nào (không có trong DOM ban đầu)
*/
public String fluentWaitAndGetResult() {
System.out.println("[Page]: Đang dùng Fluent Wait (poll 1s) để rình rập Element...");
FluentWait<WebDriver> fluentWait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(15))
.pollingEvery(Duration.ofSeconds(1))
.ignoring(NoSuchElementException.class);
WebElement result = fluentWait.until(ExpectedConditions.visibilityOfElementLocated(finishText2));
System.out.println("[Page]: Bắt được Element vừa xuất hiện!");
highlightElement(result);
return result.getText();
}
private void highlightElement(WebElement element) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('style', 'border: 3px solid red; background: yellow;');", element);
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
}
}
package com.automation.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
/**
* GooglePage - Đại diện cho trang tìm kiếm Google
* Dùng cho: Bài 13 (Robot Class)
*/
public class GooglePage {
private WebDriver driver;
// --- Locators ---
private By searchBox = By.name("q");
public GooglePage(WebDriver driver) {
this.driver = driver;
}
public void open() {
System.out.println("[Page]: Mở trang Google.com");
driver.get("https://www.google.com");
}
public void enterSearchQuery(String query) {
System.out.println("[Page]: Nhập từ khóa tìm kiếm: '" + query + "'");
WebElement box = driver.findElement(searchBox);
highlightElement(box);
box.sendKeys(query);
}
public String getTitle() {
return driver.getTitle();
}
public String getCurrentUrl() {
return driver.getCurrentUrl();
}
private void highlightElement(WebElement element) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('style', 'border: 3px solid red; background: yellow;');", element);
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
}
}
package com.automation.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
/**
* LoginPage class đại diện cho trang Đăng nhập của hệ thống CRM.
* Theo mô hình POM:
* 1. Mọi thành phần (Element) của trang này sẽ được quản lý tại đây.
* 2. Mọi hành động (Method) trên trang này cũng sẽ được viết tại đây.
*/
public class LoginPage {
private WebDriver driver;
private WebDriverWait wait;
// --- 1. Khai báo Locators (Object Repository) ---
// Chúng ta để 'private' để bảo vệ các locator, không cho Test Case sửa đổi trực tiếp.
private By emailInput = By.id("email");
private By passwordInput = By.id("password");
private By loginBtn = By.xpath("//button[@type='submit']");
private By errorMessage = By.xpath("//div[contains(@class,'alert-danger')]");
// --- 2. Hàm khởi tạo (Constructor) ---
// Khi Test Case tạo mới một đối tượng LoginPage, nó sẽ truyền 'driver' vào đây.
public LoginPage(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
// --- 3. Các hàm hành động (Page Actions) ---
public void enterEmail(String email) {
System.out.println("[Page]: Nhập Email: " + email);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(emailInput));
highlightElement(element); // Gọi hàm highlight để dễ quan sát
element.clear();
element.sendKeys(email);
}
public void enterPassword(String password) {
System.out.println("[Page]: Nhập Password...");
WebElement element = driver.findElement(passwordInput);
highlightElement(element);
element.clear();
element.sendKeys(password);
}
public void clickLogin() {
System.out.println("[Page]: Nhấn nút Login");
WebElement element = driver.findElement(loginBtn);
highlightElement(element);
element.click();
}
// Hàm nghiệp vụ tổng hợp (Business Flow)
public void login(String email, String password) {
enterEmail(email);
enterPassword(password);
clickLogin();
}
public String getErrorMessage() {
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(errorMessage));
return element.getText();
}
/**
* Hàm Highlight nội bộ trong Page để phục vụ việc quan sát.
*/
private void highlightElement(WebElement element) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('style', 'border: 3px solid red; background: yellow;');", element);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.automation.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
import java.util.Set;
/**
* WindowIFrameDemoPage - Đại diện cho các trang demo Window & iFrame
* Dùng cho: Bài 12
*/
public class WindowIFrameDemoPage {
private WebDriver driver;
private WebDriverWait wait;
// --- Locators ---
private By linkOpenNewWindow = By.linkText("Click Here");
private By pageHeader = By.tagName("h3");
private By iframeEditor = By.id("mce_0_ifr");
private By editorBody = By.id("tinymce");
public WindowIFrameDemoPage(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
public void openWindowsPage() {
System.out.println("[Page]: Mở trang Windows Demo");
driver.get("https://the-internet.herokuapp.com/windows");
}
public void openIFramePage() {
System.out.println("[Page]: Mở trang iFrame Demo");
driver.get("https://the-internet.herokuapp.com/iframe");
}
// --- Window Handling ---
public String getMainWindowHandle() {
return driver.getWindowHandle();
}
public void clickOpenNewWindow() {
System.out.println("[Page]: Click link để mở cửa sổ mới");
WebElement link = driver.findElement(linkOpenNewWindow);
highlightElement(link);
link.click();
}
public void switchToNewWindow(String mainHandle) {
System.out.println("[Page]: Chuyển sang cửa sổ mới...");
Set<String> allHandles = driver.getWindowHandles();
System.out.println("[Page]: Tổng số Tab đang mở: " + allHandles.size());
for (String handle : allHandles) {
if (!handle.equals(mainHandle)) {
driver.switchTo().window(handle);
System.out.println("[Page]: Đã vào Tab mới. Tiêu đề: " + driver.getTitle());
break;
}
}
}
public void closeCurrentWindowAndSwitch(String handle) {
System.out.println("[Page]: Đóng Tab hiện tại và quay về Tab: " + handle.substring(0, 8) + "...");
driver.close();
driver.switchTo().window(handle);
}
public String getPageTitle() {
return driver.getTitle();
}
// --- iFrame Handling ---
public String getOuterHeaderText() {
System.out.println("[Page]: Lấy tiêu đề bên NGOÀI iFrame");
WebElement header = driver.findElement(pageHeader);
highlightElement(header);
return header.getText();
}
public void switchIntoIFrame() {
System.out.println("[Page]: Chuyển VÀO bên trong iFrame");
driver.switchTo().frame("mce_0_ifr");
}
public void clearAndTypeInEditor(String text) {
System.out.println("[Page]: Xóa nội dung cũ và nhập: '" + text + "'");
WebElement editor = driver.findElement(editorBody);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].innerHTML = '';", editor);
editor.sendKeys(text);
}
public void switchOutOfIFrame() {
System.out.println("[Page]: Thoát ra NGOÀI iFrame");
driver.switchTo().defaultContent();
}
public String getOuterHeaderTextAfterSwitch() {
WebElement header = driver.findElement(pageHeader);
return header.getText();
}
private void highlightElement(WebElement element) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('style', 'border: 3px solid red; background: yellow;');", element);
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
}
}
package com.automation.testcases;
import com.automation.base.BaseSetup;
import com.automation.pages.AnhTesterPage;
import org.testng.annotations.Test;
public class BasicWebDriverCommandsTest extends BaseSetup {
@Test(description = "Bài 7: Các lệnh WebDriver cơ bản và điều hướng")
@Test(description = "Bài 7: Các lệnh WebDriver cơ bản và điều hướng (POM)")
public void testBasicCommands() throws InterruptedException {
AnhTesterPage anhTesterPage = new AnhTesterPage(driver);
System.out.println("\n========================================");
System.out.println(" BẮT ĐẦU TEST: Bài 7 - WebDriver Commands");
System.out.println("========================================\n");
// --- Bước 1: Mở trang web ---
System.out.println("[Bước 1]: Đang mở trang Anh Tester...");
driver.get("https://anhtester.com");
System.out.println("[Bước 1]: Mở trang Anh Tester...");
anhTesterPage.open();
Thread.sleep(2000);
System.out.println(" ✓ Tiêu đề trang: " + driver.getTitle());
System.out.println(" ✓ URL hiện tại: " + driver.getCurrentUrl());
System.out.println(" ✓ Tiêu đề: " + anhTesterPage.getTitle());
System.out.println(" ✓ URL: " + anhTesterPage.getCurrentUrl());
// --- Bước 2: Điều hướng sang trang khác ---
System.out.println("\n[Bước 2]: Điều hướng (navigate) sang Google...");
System.out.println("\n[Bước 2]: Điều hướng sang Google...");
driver.navigate().to("https://google.com");
Thread.sleep(2000);
System.out.println(" ✓ Đã sang trang: " + driver.getTitle());
System.out.println(" ✓ Đã sang: " + driver.getTitle());
// --- Bước 3: Quay lại (Back) ---
System.out.println("\n[Bước 3]: Nhấn Back - Quay lại trang trước...");
System.out.println("\n[Bước 3]: Nhấn Back...");
driver.navigate().back();
Thread.sleep(2000);
System.out.println(" ✓ Đã quay lại: " + driver.getTitle());
// --- Bước 4: Đi tiếp (Forward) ---
System.out.println("\n[Bước 4]: Nhấn Forward - Đi tiếp...");
System.out.println("\n[Bước 4]: Nhấn Forward...");
driver.navigate().forward();
Thread.sleep(2000);
System.out.println(" ✓ Đã đi tiếp: " + driver.getTitle());
System.out.println(" ✓ Đi tiếp: " + driver.getTitle());
// --- Bước 5: Tải lại trang (Refresh) ---
System.out.println("\n[Bước 5]: Tải lại trang (Refresh)...");
System.out.println("\n[Bước 5]: Refresh trang...");
driver.navigate().refresh();
Thread.sleep(2000);
System.out.println(" ✓ Đã tải lại: " + driver.getTitle());
System.out.println(" ✓ Đã refresh: " + driver.getTitle());
System.out.println("\n========================================");
System.out.println(" KẾT THÚC TEST: Tất cả bước PASS!");
......
package com.automation.testcases;
import com.automation.base.BaseSetup;
import com.automation.pages.CustomerPage;
import com.automation.pages.DashboardPage;
import com.automation.pages.LoginPage;
import org.testng.annotations.Test;
public class CRMTest extends BaseSetup {
@Test(description = "Quy trình Thêm mới Khách hàng hoàn chỉnh - Áp dụng Page Object Model")
public void testAddCustomerPOM() {
// --- 1. Khai báo các trang cần dùng ---
LoginPage loginPage = new LoginPage(driver);
DashboardPage dashboardPage = new DashboardPage(driver);
CustomerPage customerPage = new CustomerPage(driver);
String companyName = "POM Customer " + System.currentTimeMillis();
System.out.println("\n========================================");
System.out.println(" CHẠY TEST CRM: MÔ HÌNH PAGE OBJECT MODEL");
System.out.println("========================================\n");
// --- Bước 1: Đăng nhập ---
driver.get("https://crm.anhtester.com/admin/authentication");
loginPage.login("admin@example.com", "123456");
// --- Bước 2: Vào menu Khách hàng ---
dashboardPage.openCustomersMenu();
// --- Bước 3: Thêm mới ---
customerPage.clickNewCustomer();
customerPage.enterCustomerInfo(companyName, "VAT-POM", "0999888777", "https://pom.com");
customerPage.clickSave();
// --- Bước 4: Xác nhận ---
String headerName = customerPage.getHeaderProfileName();
System.out.println("[Test]: Kiểm tra tên công ty trên Profile...");
org.testng.Assert.assertTrue(headerName.contains(companyName), "Lỗi: Tên công ty không khớp!");
// --- Bước 5: Tìm kiếm lại ---
dashboardPage.openCustomersMenu(); // Quay lại danh sách
boolean isFound = customerPage.isCustomerDisplayedInTable(companyName);
if (isFound) {
System.out.println("[Test]: Xác nhận tìm thấy khách hàng trong bảng.");
} else {
System.out.println("[Test]: ⚠ Cảnh báo: Không tìm thấy qua Search (Index trễ).");
}
System.out.println("\n========================================");
System.out.println(" KẾT THÚC TEST: Bài 17 POM THÀNH CÔNG!");
System.out.println("========================================\n");
}
}
package com.automation.testcases;
import com.automation.base.BaseSetup;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import com.automation.pages.AnhTesterPage;
import com.automation.pages.ContextMenuDemoPage;
import com.automation.pages.DragDropDemoPage;
import org.testng.Assert;
import org.testng.annotations.Test;
public class HandleActionsTest extends BaseSetup {
@Test(priority = 1, description = "Test Mouse Hover - Di chuột qua menu")
@Test(priority = 1, description = "Bài 13: Mouse Hover (POM)")
public void testMouseHover() throws InterruptedException {
AnhTesterPage anhTesterPage = new AnhTesterPage(driver);
System.out.println("\n========================================");
System.out.println(" BẮT ĐẦU TEST: Actions - Mouse Hover");
System.out.println(" BẮT ĐẦU TEST: Actions - Mouse Hover (POM)");
System.out.println("========================================\n");
driver.get("https://anhtester.com");
anhTesterPage.open();
Thread.sleep(2000);
Actions actions = new Actions(driver);
// --- Bước 1: Tìm và highlight menu Khoá học ---
System.out.println("[Bước 1]: Tìm menu 'Khoá học'. Đang tô viền đỏ...");
WebElement menuCourses = driver.findElement(By.xpath("//a[contains(., 'Khoá học')]"));
highlightElement(menuCourses);
System.out.println("[Bước 1-2]: Di chuột vào menu 'Khoá học'...");
anhTesterPage.hoverMenuCourses();
Thread.sleep(1500);
// --- Bước 2: Thực hiện Hover ---
System.out.println("[Bước 2]: Thực hiện di chuột (Hover) vào menu...");
actions.moveToElement(menuCourses).perform();
Thread.sleep(2000);
System.out.println(" ✓ Đã hover! Menu con xuất hiện.");
// --- Bước 3: Kiểm tra menu con ---
System.out.println("[Bước 3]: Tìm và highlight menu con 'Website Testing'...");
WebElement websiteTesting = driver.findElement(By.xpath("//a[contains(., 'Website Testing')]"));
highlightElement(websiteTesting);
Assert.assertTrue(websiteTesting.isDisplayed(), "Menu con Website Testing không hiện thị sau khi hover!");
System.out.println("[Bước 3]: Kiểm tra menu con 'Website Testing'...");
boolean isVisible = anhTesterPage.isMenuWebsiteTestingDisplayed();
Assert.assertTrue(isVisible, "Menu con Website Testing không hiển thị sau hover!");
System.out.println(" ✓ Menu con hiển thị thành công!\n");
}
@Test(priority = 2, description = "Test Right Click & Double Click")
@Test(priority = 2, description = "Bài 13: Right Click & Double Click (POM)")
public void testClickActions() throws InterruptedException {
ContextMenuDemoPage contextPage = new ContextMenuDemoPage(driver);
System.out.println("\n========================================");
System.out.println(" BẮT ĐẦU TEST: Actions - Right Click & Double Click");
System.out.println(" BẮT ĐẦU TEST: Right Click & Double Click (POM)");
System.out.println("========================================\n");
driver.get("https://demo.guru99.com/test/simple_context_menu.html");
contextPage.open();
Thread.sleep(2000);
Actions actions = new Actions(driver);
// --- Bước 1: Right Click ---
System.out.println("[Bước 1]: Tìm vùng Right Click. Đang tô viền đỏ...");
WebElement rightClickBtn = driver.findElement(By.xpath("//span[contains(text(),'right click me')]"));
highlightElement(rightClickBtn);
System.out.println("[Bước 1-2]: Thực hiện Right Click...");
contextPage.rightClickOnArea();
Thread.sleep(1500);
System.out.println("[Bước 2]: Thực hiện Click Chuột Phải (Right Click)...");
actions.contextClick(rightClickBtn).perform();
Thread.sleep(2000);
WebElement copyItem = driver.findElement(By.xpath("//span[contains(text(),'Copy')]"));
Assert.assertTrue(copyItem.isDisplayed(), "Menu chuột phải không hiện thị!");
System.out.println(" ✓ Menu chuột phải đã xuất hiện!");
boolean copyVisible = contextPage.isCopyMenuItemDisplayed();
Assert.assertTrue(copyVisible, "Menu chuột phải không hiển thị!");
System.out.println(" ✓ Menu chuột phải xuất hiện!");
actions.sendKeys(Keys.ESCAPE).perform();
contextPage.dismissContextMenu();
Thread.sleep(1000);
// --- Bước 3: Double Click ---
System.out.println("[Bước 3]: Tìm nút Double Click. Đang tô viền đỏ...");
WebElement doubleClickBtn = driver
.findElement(By.xpath("//button[contains(text(),'Double-Click Me To See Alert')]"));
highlightElement(doubleClickBtn);
System.out.println("[Bước 3-4]: Thực hiện Double Click...");
contextPage.doubleClickButton();
Thread.sleep(1500);
System.out.println("[Bước 4]: Thực hiện Click Đúp (Double Click)...");
actions.doubleClick(doubleClickBtn).perform();
Thread.sleep(2000);
driver.switchTo().alert().accept();
System.out.println(" ✓ Double Click thành công, Alert đã được đóng!\n");
contextPage.acceptAlertAfterDoubleClick();
System.out.println(" ✓ Double Click thành công!\n");
}
@Test(priority = 3, description = "Test Drag and Drop - Kéo và thả")
@Test(priority = 3, description = "Bài 13: Drag and Drop (POM)")
public void testDragAndDrop() throws InterruptedException {
DragDropDemoPage dragDropPage = new DragDropDemoPage(driver);
System.out.println("\n========================================");
System.out.println(" BẮT ĐẦU TEST: Actions - Drag & Drop");
System.out.println(" BẮT ĐẦU TEST: Drag & Drop (POM)");
System.out.println("========================================\n");
driver.get("https://demo.guru99.com/test/drag_drop.html");
dragDropPage.open();
Thread.sleep(2000);
Actions actions = new Actions(driver);
// --- Bước 1: Tìm và highlight phần tử Nguồn ---
System.out.println("[Bước 1]: Tìm phần tử NGUỒN (Source - mục 5000). Đang tô viền đỏ...");
WebElement source = driver.findElement(By.xpath("//li[@id='fourth']//a[contains(text(),'5000')]"));
highlightElement(source);
Thread.sleep(1500);
// --- Bước 2: Tìm và highlight phần tử Đích ---
System.out.println("[Bước 2]: Tìm phần tử ĐÍCH (Target - ô trống). Đang tô viền đỏ...");
WebElement target = driver.findElement(By.xpath("//ol[@id='amt7']//li[@class='placeholder']"));
highlightElement(target);
Thread.sleep(1500);
// --- Bước 3: Thực hiện kéo thả ---
System.out.println("[Bước 3]: Thực hiện KÉO từ Nguồn và THẢ vào Đích...");
actions.dragAndDrop(source, target).perform();
System.out.println("[Bước 1-3]: Thực hiện Kéo & Thả phần tử '5000'...");
dragDropPage.dragAndDropItem();
Thread.sleep(2000);
// --- Bước 4: Kiểm tra kết quả ---
System.out.println("[Bước 4]: Kiểm tra và highlight phần tử sau khi kéo thả...");
WebElement result = driver.findElement(By.xpath("//ol[@id='amt7']//li[contains(text(),'5000')]"));
highlightElement(result);
Assert.assertTrue(result.isDisplayed(), "Kéo thả không thành công!");
System.out.println(" ✓ Kéo thả thành công! Phần tử '5000' đã ở vị trí mới.\n");
System.out.println("[Bước 4]: Kiểm tra kết quả...");
boolean success = dragDropPage.isResultDisplayed();
Assert.assertTrue(success, "Kéo thả không thành công!");
System.out.println(" ✓ Kéo thả thành công!\n");
}
}
package com.automation.testcases;
import com.automation.base.BaseSetup;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import com.automation.pages.AlertDemoPage;
import org.testng.Assert;
import org.testng.annotations.Test;
public class HandleAlertTest extends BaseSetup {
@Test(priority = 1, description = "Bài 11: Xử lý Simple Alert (Thông báo đơn giản)")
@Test(priority = 1, description = "Bài 11: Simple Alert (POM)")
public void testSimpleAlert() throws InterruptedException {
AlertDemoPage alertPage = new AlertDemoPage(driver);
System.out.println("\n========================================");
System.out.println(" BẮT ĐẦU TEST: Simple Alert");
System.out.println(" BẮT ĐẦU TEST: Simple Alert (POM)");
System.out.println("========================================\n");
driver.get("https://the-internet.herokuapp.com/javascript_alerts");
Thread.sleep(2000);
// --- Bước 1: Tìm và highlight nút ---
System.out.println("[Bước 1]: Tìm nút 'Click for JS Alert'. Đang tô viền đỏ...");
WebElement alertBtn = driver.findElement(By.xpath("//button[text()='Click for JS Alert']"));
highlightElement(alertBtn);
Thread.sleep(1000);
// --- Bước 2: Click để hiện Alert ---
System.out.println("[Bước 2]: Click nút để hiện Alert...");
alertBtn.click();
alertPage.open();
Thread.sleep(1500);
// --- Bước 3: Xử lý Alert ---
Alert alert = driver.switchTo().alert();
System.out.println("[Bước 3]: Đã thấy Alert bật lên! Nội dung: '" + alert.getText() + "'");
System.out.println("[Bước 4]: Nhấn OK (Accept) để đóng Alert...");
alert.accept();
String msg = alertPage.triggerSimpleAlertAndAccept();
Thread.sleep(2000);
System.out.println("[Test]: Alert đã Accept. Nội dung: '" + msg + "'");
System.out.println(" ✓ Simple Alert xử lý thành công!\n");
}
@Test(priority = 2, description = "Bài 11: Xử lý Confirm Alert (Hộp thoại Có/Không)")
@Test(priority = 2, description = "Bài 11: Confirm Alert (POM)")
public void testConfirmAlert() throws InterruptedException {
AlertDemoPage alertPage = new AlertDemoPage(driver);
System.out.println("\n========================================");
System.out.println(" BẮT ĐẦU TEST: Confirm Alert");
System.out.println(" BẮT ĐẦU TEST: Confirm Alert (POM)");
System.out.println("========================================\n");
driver.get("https://the-internet.herokuapp.com/javascript_alerts");
Thread.sleep(2000);
// --- Bước 1: Tìm và highlight nút Confirm ---
System.out.println("[Bước 1]: Tìm nút 'Click for JS Confirm'. Đang tô viền đỏ...");
WebElement confirmBtn = driver.findElement(By.xpath("//button[text()='Click for JS Confirm']"));
highlightElement(confirmBtn);
Thread.sleep(1000);
// --- Bước 2: Click để hiện Confirm Alert ---
System.out.println("[Bước 2]: Click nút để hiện Confirm Alert...");
confirmBtn.click();
alertPage.open();
Thread.sleep(1500);
// --- Bước 3: Xử lý Alert ---
Alert alert = driver.switchTo().alert();
System.out.println("[Bước 3]: Confirm Alert hiện ra! Nội dung: '" + alert.getText() + "'");
System.out.println("[Bước 4]: Nhấn CANCEL (Dismiss) - Chọn 'Không'...");
alert.dismiss();
Thread.sleep(2000);
String msg = alertPage.triggerConfirmAlertAndDismiss();
Thread.sleep(1500);
System.out.println("[Test]: Confirm Alert đã Dismiss. Nội dung: '" + msg + "'");
// --- Bước 5: Xác nhận kết quả ---
System.out.println("[Bước 5]: Tìm và highlight kết quả trả về...");
WebElement result = driver.findElement(By.id("result"));
highlightElement(result);
System.out.println(" ✓ Kết quả: " + result.getText());
Assert.assertTrue(result.getText().contains("Cancel"), "Kết quả không phải Cancel!");
String result = alertPage.getResultText();
System.out.println("[Test]: Kết quả: " + result);
Assert.assertTrue(result.contains("Cancel"), "Kết quả không phải Cancel!");
}
@Test(priority = 3, description = "Bài 11: Xử lý Prompt Alert (Hộp thoại nhập chữ)")
@Test(priority = 3, description = "Bài 11: Prompt Alert (POM)")
public void testPromptAlert() throws InterruptedException {
AlertDemoPage alertPage = new AlertDemoPage(driver);
System.out.println("\n========================================");
System.out.println(" BẮT ĐẦU TEST: Prompt Alert");
System.out.println(" BẮT ĐẦU TEST: Prompt Alert (POM)");
System.out.println("========================================\n");
driver.get("https://the-internet.herokuapp.com/javascript_alerts");
Thread.sleep(2000);
// --- Bước 1: Tìm và highlight nút Prompt ---
System.out.println("[Bước 1]: Tìm nút 'Click for JS Prompt'. Đang tô viền đỏ...");
WebElement promptBtn = driver.findElement(By.xpath("//button[text()='Click for JS Prompt']"));
highlightElement(promptBtn);
Thread.sleep(1000);
// --- Bước 2: Click để hiện Prompt Alert ---
System.out.println("[Bước 2]: Click nút để hiện Prompt Alert...");
promptBtn.click();
alertPage.open();
Thread.sleep(1500);
// --- Bước 3: Nhập chữ vào Alert ---
Alert alert = driver.switchTo().alert();
System.out.println("[Bước 3]: Prompt Alert hiện ra! Đang gõ tên vào ô nhập chữ...");
alert.sendKeys("Anh Tester");
alertPage.triggerPromptAlertSendKeysAndAccept("Anh Tester");
Thread.sleep(1500);
System.out.println("[Bước 4]: Nhấn OK (Accept)...");
alert.accept();
Thread.sleep(2000);
// --- Bước 5: Xác nhận kết quả ---
System.out.println("[Bước 5]: Tìm và highlight kết quả trả về...");
WebElement result = driver.findElement(By.id("result"));
highlightElement(result);
System.out.println(" ✓ Kết quả: " + result.getText());
Assert.assertTrue(result.getText().contains("Anh Tester"), "Tên không đúng trong kết quả!");
String result = alertPage.getResultText();
System.out.println("[Test]: Kết quả Prompt: " + result);
Assert.assertTrue(result.contains("Anh Tester"), "Tên không đúng trong kết quả!");
}
}
package com.automation.testcases;
import com.automation.base.BaseSetup;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import com.automation.pages.AnhTesterPage;
import com.automation.pages.CmsLoginPage;
import org.testng.Assert;
import org.testng.annotations.Test;
public class HandleJavascriptExecutorTest extends BaseSetup {
@Test(priority = 1, description = "Bài 14 - Kịch bản 1: Ép nhập text bằng JS (Vượt thuộc tính readonly/disabled)")
@Test(priority = 1, description = "Bài 14 - KBản 1: Ép nhập text bằng JS (POM)")
public void testForceSendKeysJS() throws InterruptedException {
// Sử dụng trang CRM chuẩn của Anh Tester
driver.get("https://cms.anhtester.com/login");
JavascriptExecutor js = (JavascriptExecutor) driver;
CmsLoginPage cmsLoginPage = new CmsLoginPage(driver);
WebElement emailInput = driver.findElement(By.id("email"));
System.out.println("\n[Bước 1]: Đã tìm thấy ô Email. Đang tô viền đỏ (Highlight)...");
highlightElement(emailInput);
Thread.sleep(1500); // Tạm dừng 1.5s để user kịp nhìn viền đỏ
cmsLoginPage.open();
Thread.sleep(1500);
System.out.println("[Bước 2]: Gán giá trị 'admin@example.com' bằng Javascript...");
js.executeScript("arguments[0].value = 'admin@example.com';", emailInput);
System.out.println("\n[Bước 1-2]: Gán email bằng JS vào ô Email...");
cmsLoginPage.setEmailByJS("admin@example.com");
String actualValue = (String) js.executeScript("return arguments[0].value;", emailInput);
System.out.println("[Bước 3]: Kiểm tra lại kết quả. Giá trị hiện tại: " + actualValue);
String actualValue = cmsLoginPage.getEmailValueByJS();
System.out.println("[Bước 3]: Giá trị hiện tại: " + actualValue);
Assert.assertEquals(actualValue, "admin@example.com");
Thread.sleep(2000);
}
@Test(priority = 2, description = "Bài 14 - Kịch bản 2: Click bằng JS (Xử lý lỗi ElementClickIntercepted)")
@Test(priority = 2, description = "Bài 14 - KBản 2: Click bằng JS (POM)")
public void testForceClickJS() throws InterruptedException {
driver.get("https://cms.anhtester.com/login");
JavascriptExecutor js = (JavascriptExecutor) driver;
// Xóa email và password mặc định nếu có (trang CRM thường điền sẵn)
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("password")).clear();
CmsLoginPage cmsLoginPage = new CmsLoginPage(driver);
WebElement loginBtn = driver.findElement(By.xpath("//button[normalize-space()='Login']"));
System.out.println("\n[Bước 1]: Đã tìm thấy nút Login. Đang tô viền đỏ (Highlight)...");
highlightElement(loginBtn);
cmsLoginPage.open();
Thread.sleep(1500);
System.out.println("[Bước 2]: Dùng JS kích hoạt sự kiện Click xuyên qua mọi vật cản UI...");
js.executeScript("arguments[0].click();", loginBtn);
cmsLoginPage.getEmailInput().clear();
cmsLoginPage.getPasswordInput().clear();
System.out.println("\n[Bước 1-2]: Click Login bằng JS (xuyên qua mọi vật cản)...");
cmsLoginPage.clickLoginWithJS();
Thread.sleep(2000);
System.out.println("[Bước 3]: Kiểm tra URL sau khi click...");
String currentUrl = driver.getCurrentUrl();
Assert.assertTrue(currentUrl.contains("login"), "Đáng lẽ không thể login nhưng lại thành công!");
System.out.println("[Bước 3]: Kiểm tra URL...");
String currentUrl = cmsLoginPage.getCurrentUrl();
Assert.assertTrue(currentUrl.contains("login"), "Đáng lẽ login thất bại nhưng lại thành công!");
}
@Test(priority = 3, description = "Bài 14 - Kịch bản 3: Cuộn trang phức tạp (Kích hoạt Lazy load)")
@Test(priority = 3, description = "Bài 14 - KBản 3: Cuộn trang bằng JS (POM)")
public void testScrollJS() throws InterruptedException {
driver.get("https://anhtester.com/");
JavascriptExecutor js = (JavascriptExecutor) driver;
AnhTesterPage anhTesterPage = new AnhTesterPage(driver);
anhTesterPage.open();
Thread.sleep(2000);
System.out.println("\n[Bước 1]: Đang cuộn mạnh xuống cuối cùng của trang web...");
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
System.out.println("\n[Bước 1]: Cuộn xuống cuối trang...");
anhTesterPage.scrollToBottom();
Thread.sleep(2000);
System.out.println("[Bước 2]: Đang cuộn ngược lên một chút (bằng tọa độ)...");
js.executeScript("window.scrollBy(0, -1500)");
System.out.println("[Bước 2]: Cuộn ngược lên 1500px...");
anhTesterPage.scrollUp(1500);
Thread.sleep(2000);
}
}
package com.automation.testcases;
import com.automation.base.BaseSetup;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import com.automation.pages.GooglePage;
import org.testng.annotations.Test;
import java.awt.*;
......@@ -10,38 +9,32 @@ import java.awt.event.KeyEvent;
public class HandleRobotClassTest extends BaseSetup {
@Test(description = "Bài 13: Dùng Robot Class để điều khiển bàn phím cấp hệ điều hành")
@Test(description = "Bài 13: Robot Class điều khiển bàn phím OS (POM)")
public void testRobotClass() throws AWTException, InterruptedException {
GooglePage googlePage = new GooglePage(driver);
System.out.println("\n========================================");
System.out.println(" BẮT ĐẦU TEST: Bài 13 - Robot Class");
System.out.println(" BẮT ĐẦU TEST: Bài 13 - Robot Class (POM)");
System.out.println("========================================\n");
driver.get("https://www.google.com");
System.out.println("[Bước 1]: Mở trang Google...");
googlePage.open();
Thread.sleep(2000);
// --- Bước 1: Tìm ô tìm kiếm ---
System.out.println("[Bước 1]: Tìm ô tìm kiếm Google bằng By.name('q'). Đang tô viền đỏ...");
WebElement searchBox = driver.findElement(By.name("q"));
highlightElement(searchBox);
Thread.sleep(1000);
// --- Bước 2: Nhập chữ vào ô tìm kiếm ---
System.out.println("[Bước 2]: Nhập từ khóa tìm kiếm bằng Selenium sendKeys()...");
searchBox.sendKeys("Selenium Java Robot Class");
System.out.println("[Bước 2]: Nhập từ khóa tìm kiếm...");
googlePage.enterSearchQuery("Selenium Java Robot Class");
Thread.sleep(2000);
// --- Bước 3: Dùng Robot Class nhấn phím Enter ---
System.out.println("[Bước 3]: Dùng ROBOT CLASS nhấn phím ENTER (lệnh cấp hệ điều hành)...");
System.out.println(" ⚡ Đây là điểm mạnh của Robot: Bấm phím trực tiếp vào OS, không qua Selenium!");
System.out.println("[Bước 3]: Dùng ROBOT CLASS nhấn Enter (lệnh cấp OS)...");
System.out.println(" ⚡ Robot bấm phím trực tiếp vào OS, không qua Selenium!");
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(3000);
// --- Bước 4: Xác nhận kết quả ---
System.out.println("[Bước 4]: Kiểm tra kết quả tìm kiếm...");
System.out.println(" ✓ URL hiện tại: " + driver.getCurrentUrl());
System.out.println(" ✓ Tiêu đề trang: " + driver.getTitle());
System.out.println("[Bước 4]: Kết quả tìm kiếm...");
System.out.println(" ✓ URL: " + googlePage.getCurrentUrl());
System.out.println(" ✓ Title: " + googlePage.getTitle());
System.out.println("\n========================================");
System.out.println(" KẾT THÚC TEST: Robot Class hoạt động!");
......
package com.automation.testcases;
import com.automation.base.BaseSetup;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.automation.pages.DynamicLoadingPage;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.time.Duration;
public class HandleWaitTest extends BaseSetup {
@Test(priority = 1, description = "Bài 15 - Kịch bản 1: Explicit Wait chờ Loading Spinner biến mất")
@Test(priority = 1, description = "Bài 15 - Explicit Wait chờ Spinner biến mất (POM)")
public void testWaitSpinnerDisappear() throws InterruptedException {
driver.get("https://the-internet.herokuapp.com/dynamic_loading/1");
DynamicLoadingPage loadingPage = new DynamicLoadingPage(driver);
WebElement startBtn = driver.findElement(By.xpath("//button[text()='Start']"));
System.out.println("\n[Bước 1]: Đã thấy nút Start. Đang tô viền đỏ...");
highlightElement(startBtn);
Thread.sleep(1500); // Tạm dừng để user thấy viền đỏ
startBtn.click();
System.out.println("\n[Bước 1]: Mở trang Dynamic Loading Ví dụ 1...");
loadingPage.openExample1();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
System.out.println("[Bước 2]: Click Start...");
loadingPage.clickStart();
Thread.sleep(500);
System.out.println("[Bước 2]: Web đang xử lý (hiện Loading Spinner). Đang dùng Explicit Wait để canh gác...");
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("loading")));
System.out.println("[Bước 3]: Loading Spinner đã biến mất hoàn toàn! Bắt đầu lấy kết quả...");
WebElement finishText = driver.findElement(By.id("finish"));
highlightElement(finishText);
System.out.println("[Bước 4]: Kết quả là: " + finishText.getText());
Assert.assertTrue(finishText.isDisplayed(), "Dữ liệu chưa load xong!");
System.out.println("[Bước 3]: Explicit Wait chờ Spinner biến mất...");
String result = loadingPage.waitForSpinnerAndGetResult();
System.out.println("[Bước 4]: Kết quả: " + result);
Assert.assertTrue(result.contains("Hello World!"), "Dữ liệu chưa load xong!");
}
@Test(priority = 2, description = "Bài 15 - Kịch bản 2: Fluent Wait chờ Element ngẫu nhiên")
@Test(priority = 2, description = "Bài 15 - Fluent Wait chờ Element xuất hiện (POM)")
public void testFluentWait() throws InterruptedException {
driver.get("https://the-internet.herokuapp.com/dynamic_loading/2");
DynamicLoadingPage loadingPage = new DynamicLoadingPage(driver);
WebElement startBtn = driver.findElement(By.xpath("//button[text()='Start']"));
System.out.println("\n[Bước 1]: Đã thấy nút Start. Đang tô viền đỏ...");
highlightElement(startBtn);
Thread.sleep(1500);
startBtn.click();
System.out.println("\n[Bước 1]: Mở trang Dynamic Loading Ví dụ 2...");
loadingPage.openExample2();
// Khởi tạo Fluent Wait: Chờ tối đa 15s, cứ 1s tìm 1 lần, bỏ qua lỗi NoSuchElementException
FluentWait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(15))
.pollingEvery(Duration.ofSeconds(1))
.ignoring(NoSuchElementException.class);
System.out.println("[Bước 2]: Click Start...");
loadingPage.clickStart();
Thread.sleep(500);
System.out.println("[Bước 2]: Đang dùng Fluent Wait (tìm 1 lần / giây) để rình rập Element...");
// Element ở trang số 2 này ban đầu hoàn toàn KHÔNG CÓ TRONG DOM.
// Phải dùng FluentWait để nó lặp lại việc tìm kiếm mà không văng lỗi sảng.
WebElement finishText = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='finish']/h4")));
System.out.println("[Bước 3]: Đã bắt được Element lúc nó vừa xuất hiện! Đang tô viền đỏ...");
highlightElement(finishText);
Thread.sleep(1500); // Nhìn viền đỏ 1.5s
System.out.println("[Bước 4]: Kết quả: " + finishText.getText());
Assert.assertEquals(finishText.getText(), "Hello World!");
System.out.println("[Bước 3]: Fluent Wait rình rập Element xuất hiện...");
String result = loadingPage.fluentWaitAndGetResult();
System.out.println("[Bước 4]: Kết quả: " + result);
Assert.assertEquals(result, "Hello World!");
}
}
package com.automation.testcases;
import com.automation.base.BaseSetup;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import com.automation.pages.WindowIFrameDemoPage;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.Set;
public class HandleWindowIFrameTest extends BaseSetup {
@Test(priority = 1, description = "Bài 12: Xử lý chuyển đổi giữa nhiều Tab (Windows)")
@Test(priority = 1, description = "Bài 12: Xử lý Tab/Windows (POM)")
public void testHandleWindows() throws InterruptedException {
WindowIFrameDemoPage windowPage = new WindowIFrameDemoPage(driver);
System.out.println("\n========================================");
System.out.println(" BẮT ĐẦU TEST: Xử lý Tab/Windows");
System.out.println(" BẮT ĐẦU TEST: Xử lý Tab/Windows (POM)");
System.out.println("========================================\n");
driver.get("https://the-internet.herokuapp.com/windows");
windowPage.openWindowsPage();
Thread.sleep(2000);
// --- Bước 1: Ghi nhớ handle của Tab hiện tại ---
String mainWindowHandle = driver.getWindowHandle();
System.out.println("[Bước 1]: Đang ở Tab chính. Handle: " + mainWindowHandle.substring(0, 8) + "...");
System.out.println("[Bước 1]: Ghi nhớ handle Tab chính...");
String mainHandle = windowPage.getMainWindowHandle();
// --- Bước 2: Click để mở Tab mới ---
System.out.println("[Bước 2]: Tìm và highlight link 'Click Here'. Chuẩn bị click mở Tab mới...");
WebElement clickHereLink = driver.findElement(By.linkText("Click Here"));
highlightElement(clickHereLink);
Thread.sleep(1000);
clickHereLink.click();
Thread.sleep(3000);
// --- Bước 3: Chuyển sang Tab mới ---
System.out.println("[Bước 3]: Đã mở Tab mới! Đang chuyển sang Tab đó...");
Set<String> allWindowHandles = driver.getWindowHandles();
System.out.println(" ✓ Tổng số Tab đang mở: " + allWindowHandles.size());
for (String handle : allWindowHandles) {
if (!handle.equals(mainWindowHandle)) {
driver.switchTo().window(handle);
Thread.sleep(2000);
System.out.println("[Bước 4]: Đã chuyển sang Tab mới. Tiêu đề: '" + driver.getTitle() + "'");
break;
}
}
// --- Bước 5: Đóng Tab mới và quay về ---
System.out.println("[Bước 5]: Đóng Tab mới và quay trở về Tab chính...");
driver.close();
driver.switchTo().window(mainWindowHandle);
System.out.println("[Bước 2]: Click mở Tab mới...");
windowPage.clickOpenNewWindow();
Thread.sleep(2000);
System.out.println(" ✓ Đã quay về Tab chính: '" + driver.getTitle() + "'");
Assert.assertTrue(driver.getTitle().contains("The Internet"), "Không quay về được Tab chính!");
System.out.println("[Bước 3]: Chuyển sang Tab mới...");
windowPage.switchToNewWindow(mainHandle);
Thread.sleep(2000);
System.out.println("[Bước 4]: Đóng Tab mới, quay về Tab chính...");
windowPage.closeCurrentWindowAndSwitch(mainHandle);
Thread.sleep(1500);
String title = windowPage.getPageTitle();
System.out.println("[Test]: Tiêu đề Tab chính: " + title);
Assert.assertTrue(title.contains("The Internet"), "Không quay về được Tab chính!");
}
@Test(priority = 2, description = "Bài 12: Xử lý iFrame (Trang web bên trong trang web)")
@Test(priority = 2, description = "Bài 12: Xử lý iFrame (POM)")
public void testHandleIFrame() throws InterruptedException {
WindowIFrameDemoPage iframePage = new WindowIFrameDemoPage(driver);
System.out.println("\n========================================");
System.out.println(" BẮT ĐẦU TEST: Xử lý iFrame");
System.out.println(" BẮT ĐẦU TEST: Xử lý iFrame (POM)");
System.out.println("========================================\n");
driver.get("https://the-internet.herokuapp.com/iframe");
Thread.sleep(3000);
iframePage.openIFramePage();
Thread.sleep(2000);
// --- Bước 1: Xác nhận đang ở bên NGOÀI iFrame ---
System.out.println("[Bước 1]: Đang ở bên NGOÀI iFrame. Tìm và highlight tiêu đề trang...");
WebElement header = driver.findElement(By.tagName("h3"));
highlightElement(header);
System.out.println(" ✓ Tiêu đề ngoài iFrame: '" + header.getText() + "'");
Thread.sleep(1500);
System.out.println("[Bước 1]: Kiểm tra bên NGOÀI iFrame...");
String outerHeader = iframePage.getOuterHeaderText();
System.out.println("[Test]: Tiêu đề ngoài iFrame: " + outerHeader);
// --- Bước 2: Chuyển VÀO iFrame ---
System.out.println("[Bước 2]: Đang chuyển VÀO bên trong iFrame 'mce_0_ifr'...");
driver.switchTo().frame("mce_0_ifr");
System.out.println("[Bước 2]: Chuyển VÀO iFrame...");
iframePage.switchIntoIFrame();
Thread.sleep(1000);
System.out.println(" ✓ Đã ở TRONG iFrame! Các lệnh find giờ chỉ tìm trong iFrame này.");
// --- Bước 3: Thao tác bên trong iFrame ---
System.out.println("[Bước 3]: Tìm ô soạn thảo và xóa nội dung cũ bằng JS...");
WebElement editor = driver.findElement(By.id("tinymce"));
org.openqa.selenium.JavascriptExecutor js = (org.openqa.selenium.JavascriptExecutor) driver;
js.executeScript("arguments[0].innerHTML = '';", editor);
Thread.sleep(1000);
System.out.println("[Bước 4]: Nhập nội dung mới vào ô soạn thảo...");
editor.sendKeys("Xin chào từ Anh Tester - Học Selenium Java!");
System.out.println("[Bước 3]: Nhập nội dung vào editor...");
iframePage.clearAndTypeInEditor("Xin chào từ Anh Tester - Học Selenium Java!");
Thread.sleep(2000);
// --- Bước 5: Thoát ra bên ngoài ---
System.out.println("[Bước 5]: Thoát ra NGOÀI iFrame (defaultContent)...");
driver.switchTo().defaultContent();
Thread.sleep(1500);
System.out.println(" ✓ Đã thoát ra ngoài iFrame thành công!");
System.out.println("[Bước 4]: Thoát ra NGOÀI iFrame...");
iframePage.switchOutOfIFrame();
Thread.sleep(1000);
WebElement headerText = driver.findElement(By.tagName("h3"));
Assert.assertTrue(headerText.getText().contains("An iFrame"), "Không thoát được khỏi iFrame!");
String headerAfter = iframePage.getOuterHeaderTextAfterSwitch();
Assert.assertTrue(headerAfter.contains("An iFrame"), "Không thoát được khỏi iFrame!");
System.out.println("[Test]: ✓ Xử lý iFrame thành công!");
}
}
package com.automation.testcases;
import com.automation.base.BaseSetup;
import com.automation.pages.LoginPage;
import org.testng.annotations.Test;
/**
* LoginTest kế thừa BaseSetup để có driver.
* Nó sẽ sử dụng LoginPage để thực hiện các thao tác.
*/
public class LoginTest extends BaseSetup {
@Test(description = "Kiểm thử đăng nhập thành công áp dụng mô hình POM")
public void testLoginSuccess() {
// --- 1. Khởi tạo đối tượng Page ---
// Chúng ta truyền 'driver' từ BaseSetup vào để LoginPage có thể sử dụng.
LoginPage loginPage = new LoginPage(driver);
System.out.println("========================================");
System.out.println(" CHẠY TEST: Login POM");
System.out.println("========================================\n");
// --- 2. Thực hiện kịch bản ---
driver.get("https://crm.anhtester.com/admin/authentication");
// Bạn thấy không? Code ở đây cực kỳ sạch, không hề có By.xpath hay By.id
loginPage.enterEmail("admin@example.com");
loginPage.enterPassword("123456");
loginPage.clickLogin();
System.out.println("\n[Test]: Đã thực hiện xong các bước đăng nhập.");
System.out.println("========================================\n");
}
@Test(description = "Kiểm thử đăng nhập thất bại với POM")
public void testLoginFail() {
LoginPage loginPage = new LoginPage(driver);
driver.get("https://crm.anhtester.com/admin/authentication");
// Sử dụng hàm nghiệp vụ tổng hợp (login) đã viết trong Page
loginPage.login("invalid@example.com", "wrongpass");
String error = loginPage.getErrorMessage();
System.out.println("[Test]: Thông báo lỗi hiển thị là: " + error);
}
}
package com.automation.testcases;
import com.automation.base.BaseSetup;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.automation.pages.CmsLoginPage;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.time.Duration;
public class WebElementCommandsTest extends BaseSetup {
@Test(description = "Bài 9: Các lệnh tương tác với WebElement")
@Test(description = "Bài 9: Tương tác với WebElement trên CMS Login (POM)")
public void testFindAndInteractWithElements() throws InterruptedException {
CmsLoginPage cmsLoginPage = new CmsLoginPage(driver);
System.out.println("\n========================================");
System.out.println(" BẮT ĐẦU TEST: Bài 9 - WebElement Commands");
System.out.println(" BẮT ĐẦU TEST: Bài 9 - WebElement Commands (POM)");
System.out.println("========================================\n");
driver.get("https://cms.anhtester.com/login");
cmsLoginPage.open();
Thread.sleep(2000);
// --- Bước 1: Tìm và highlight ô Email ---
System.out.println("[Bước 1]: Tìm ô Email bằng By.id('email'). Đang tô viền đỏ...");
WebElement inputEmail = driver.findElement(By.id("email"));
highlightElement(inputEmail);
inputEmail.clear();
// --- Bước 2: Nhập text vào ô Email ---
System.out.println("[Bước 2]: Dùng lệnh sendKeys() để nhập email...");
inputEmail.sendKeys("admin@example.com");
System.out.println("[Bước 1-2]: Nhập Email...");
cmsLoginPage.enterEmail("admin@example.com");
Thread.sleep(1500);
// --- Bước 3: Tìm và highlight ô Password ---
System.out.println("[Bước 3]: Tìm ô Password bằng By.id('password'). Đang tô viền đỏ...");
WebElement inputPassword = driver.findElement(By.id("password"));
highlightElement(inputPassword);
inputPassword.clear();
// --- Bước 4: Nhập text vào ô Password ---
System.out.println("[Bước 4]: Dùng lệnh sendKeys() để nhập mật khẩu...");
inputPassword.sendKeys("123456");
Thread.sleep(2000);
// --- Bước 5: Dùng Explicit Wait để chờ nút Login sẵn sàng ---
System.out.println("[Bước 5]: Dùng Explicit Wait chờ nút Login sẵn sàng...");
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement loginBtn = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@type='submit']")));
// --- Bước 6: Highlight và Click nút Login ---
System.out.println("[Bước 6]: Tìm thấy nút Login! Đang tô viền đỏ...");
highlightElement(loginBtn);
System.out.println("[Bước 3-4]: Nhập Password...");
cmsLoginPage.enterPassword("123456");
Thread.sleep(1500);
System.out.println("[Bước 7]: Dùng JS Click để ấn nút Login (xuyên qua mọi vật cản)...");
org.openqa.selenium.JavascriptExecutor js = (org.openqa.selenium.JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", loginBtn);
System.out.println("[Bước 5-7]: Click Login bằng JS...");
cmsLoginPage.clickLoginWithJS();
Thread.sleep(3000);
// --- Bước 8: Xác nhận kết quả ---
System.out.println("[Bước 8]: Kiểm tra URL sau khi Login...");
String currentUrl = driver.getCurrentUrl();
System.out.println(" ✓ URL sau khi login: " + currentUrl);
Assert.assertFalse(currentUrl.contains("login"), "Login thất bại, vẫn còn ở trang Login!");
String currentUrl = cmsLoginPage.getCurrentUrl();
System.out.println(" ✓ URL: " + currentUrl);
Assert.assertFalse(currentUrl.contains("login"), "Login thất bại!");
System.out.println("\n========================================");
System.out.println(" KẾT THÚC TEST: Login thành công!");
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment