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

Áp dụng Highlight & Step Logging cho toàn bộ test class trong src

parent 588d6ee8
package com.automation.testcases; package com.automation.testcases;
import org.openqa.selenium.WebDriver; import com.automation.base.BaseSetup;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import java.time.Duration; public class BasicWebDriverCommandsTest extends BaseSetup {
public class BasicWebDriverCommandsTest { @Test(description = "Bài 7: Các lệnh WebDriver cơ bản và điều hướng")
WebDriver driver;
@BeforeMethod
public void setUp() {
// Khởi tạo WebDriver
ChromeOptions options = new ChromeOptions();
options.addArguments("--no-sandbox");
options.addArguments("--disable-dev-shm-usage");
options.addArguments("--remote-allow-origins=*");
driver = new ChromeDriver(options);
// --- 4. Thiết lập thời gian chờ (Wait Configurations) ---
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));
// --- 3. Quản lý cửa sổ (Window Management) ---
driver.manage().window().maximize(); // Phóng to toàn màn hình
}
@Test
public void testBasicCommands() throws InterruptedException { public void testBasicCommands() throws InterruptedException {
// --- 1. Các hàm cơ bản (Basic Browser Operations) ---
System.out.println("Mở trang web Anh Tester...");
driver.get("https://anhtester.com");
System.out.println("Tiêu đề trang: " + driver.getTitle());
System.out.println("URL hiện tại: " + driver.getCurrentUrl());
System.out.println("Độ dài mã nguồn: " + driver.getPageSource().length()); System.out.println("\n========================================");
System.out.println(" BẮT ĐẦU TEST: Bài 7 - WebDriver Commands");
System.out.println("========================================\n");
Thread.sleep(2000); // Demo mục đích quan sát // --- Bước 1: Mở trang web ---
System.out.println("[Bước 1]: Đang mở trang Anh Tester...");
driver.get("https://anhtester.com");
Thread.sleep(2000);
System.out.println(" ✓ Tiêu đề trang: " + driver.getTitle());
System.out.println(" ✓ URL hiện tại: " + driver.getCurrentUrl());
// --- 2. Các hàm điều hướng (Navigation Operations) --- // --- Bước 2: Điều hướng sang trang khác ---
System.out.println("\nChuyển hướng sang Google..."); System.out.println("\n[Bước 2]: Điều hướng (navigate) sang Google...");
driver.navigate().to("https://google.com"); driver.navigate().to("https://google.com");
System.out.println("Đã chuyển sang: " + driver.getTitle());
Thread.sleep(2000); Thread.sleep(2000);
System.out.println(" ✓ Đã sang trang: " + driver.getTitle());
System.out.println("Quay lại (Back)..."); // --- Bước 3: Quay lại (Back) ---
System.out.println("\n[Bước 3]: Nhấn Back - Quay lại trang trước...");
driver.navigate().back(); driver.navigate().back();
System.out.println("Trang hiện tại: " + driver.getTitle());
Thread.sleep(2000); Thread.sleep(2000);
System.out.println(" ✓ Đã quay lại: " + driver.getTitle());
System.out.println("Đi tới (Forward)..."); // --- Bước 4: Đi tiếp (Forward) ---
System.out.println("\n[Bước 4]: Nhấn Forward - Đi tiếp...");
driver.navigate().forward(); driver.navigate().forward();
Thread.sleep(2000);
System.out.println(" ✓ Đã đi tiếp: " + driver.getTitle());
System.out.println("Tải lại trang (Refresh)..."); // --- Bước 5: Tải lại trang (Refresh) ---
System.out.println("\n[Bước 5]: Tải lại trang (Refresh)...");
driver.navigate().refresh(); driver.navigate().refresh();
} Thread.sleep(2000);
System.out.println(" ✓ Đã tải lại: " + driver.getTitle());
@AfterMethod System.out.println("\n========================================");
public void tearDown() { System.out.println(" KẾT THÚC TEST: Tất cả bước PASS!");
if (driver != null) { System.out.println("========================================\n");
driver.quit(); // Đóng toàn bộ trình duyệt
}
} }
} }
...@@ -11,75 +11,109 @@ import org.testng.annotations.Test; ...@@ -11,75 +11,109 @@ import org.testng.annotations.Test;
public class HandleActionsTest extends BaseSetup { public class HandleActionsTest extends BaseSetup {
@Test(priority = 1, description = "Test Mouse Hover - Di chuột qua menu") @Test(priority = 1, description = "Test Mouse Hover - Di chuột qua menu")
public void testMouseHover() { public void testMouseHover() throws InterruptedException {
System.out.println("\n========================================");
System.out.println(" BẮT ĐẦU TEST: Actions - Mouse Hover");
System.out.println("========================================\n");
driver.get("https://anhtester.com"); driver.get("https://anhtester.com");
Thread.sleep(2000);
// Khởi tạo Actions class
Actions actions = new Actions(driver); Actions actions = new Actions(driver);
// Tìm element menu "Khoá học" (Dùng 'oá' thay vì 'óa' cho đúng font của web) // --- 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')]")); WebElement menuCourses = driver.findElement(By.xpath("//a[contains(., 'Khoá học')]"));
// => GỌI HÀM HIGHLIGHT TỪ BASE
highlightElement(menuCourses); highlightElement(menuCourses);
Thread.sleep(1500);
// Thực hiện di chuột (Hover) // --- 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(); actions.moveToElement(menuCourses).perform();
Thread.sleep(2000);
System.out.println("Da thuc hien hover vao menu Khoa hoc"); System.out.println(" ✓ Đã hover! Menu con xuất hiện.");
// Kiểm tra xem menu con "Website Testing" có hiển thị không // --- 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')]")); WebElement websiteTesting = driver.findElement(By.xpath("//a[contains(., 'Website Testing')]"));
Assert.assertTrue(websiteTesting.isDisplayed(), "Menu con Website Testing khong hien thi sau khi hover!"); highlightElement(websiteTesting);
Assert.assertTrue(websiteTesting.isDisplayed(), "Menu con Website Testing không hiện thị sau khi 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 = "Test Right Click & Double Click")
public void testClickActions() { public void testClickActions() throws InterruptedException {
System.out.println("\n========================================");
System.out.println(" BẮT ĐẦU TEST: Actions - Right Click & Double Click");
System.out.println("========================================\n");
driver.get("https://demo.guru99.com/test/simple_context_menu.html"); driver.get("https://demo.guru99.com/test/simple_context_menu.html");
Thread.sleep(2000);
Actions actions = new Actions(driver); Actions actions = new Actions(driver);
// 1. Right Click (Chuột phải) // --- 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')]")); WebElement rightClickBtn = driver.findElement(By.xpath("//span[contains(text(),'right click me')]"));
highlightElement(rightClickBtn); // => HIGHLIGHT NÚT CHUỘT PHẢI highlightElement(rightClickBtn);
Thread.sleep(1500);
System.out.println("[Bước 2]: Thực hiện Click Chuột Phải (Right Click)...");
actions.contextClick(rightClickBtn).perform(); actions.contextClick(rightClickBtn).perform();
Thread.sleep(2000);
// Kiểm tra xem menu chuột phải có hiện ra không
WebElement copyItem = driver.findElement(By.xpath("//span[contains(text(),'Copy')]")); WebElement copyItem = driver.findElement(By.xpath("//span[contains(text(),'Copy')]"));
Assert.assertTrue(copyItem.isDisplayed(), "Menu chuot phai khong hien thi!"); 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!");
// Click phím ESC để đóng menu chuột phải
actions.sendKeys(Keys.ESCAPE).perform(); actions.sendKeys(Keys.ESCAPE).perform();
Thread.sleep(1000);
// 2. Double Click (Click đúp) // --- 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')]")); WebElement doubleClickBtn = driver.findElement(By.xpath("//button[contains(text(),'Double-Click Me To See Alert')]"));
highlightElement(doubleClickBtn); // => HIGHLIGHT NÚT CLICK ĐÚP highlightElement(doubleClickBtn);
Thread.sleep(1500);
System.out.println("[Bước 4]: Thực hiện Click Đúp (Double Click)...");
actions.doubleClick(doubleClickBtn).perform(); actions.doubleClick(doubleClickBtn).perform();
Thread.sleep(2000);
// Chờ và kiểm tra Alert xuất hiện
driver.switchTo().alert().accept(); driver.switchTo().alert().accept();
System.out.println("Da thuc hien Double Click va dong Alert"); System.out.println(" ✓ Double Click thành công, Alert đã được đóng!\n");
} }
@Test(priority = 3, description = "Test Drag and Drop - Kéo và thả") @Test(priority = 3, description = "Test Drag and Drop - Kéo và thả")
public void testDragAndDrop() { public void testDragAndDrop() throws InterruptedException {
System.out.println("\n========================================");
System.out.println(" BẮT ĐẦU TEST: Actions - Drag & Drop");
System.out.println("========================================\n");
driver.get("https://demo.guru99.com/test/drag_drop.html"); driver.get("https://demo.guru99.com/test/drag_drop.html");
Thread.sleep(2000);
Actions actions = new Actions(driver); Actions actions = new Actions(driver);
// Tìm phần tử nguồn (Source) và đích (Target) // --- 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')]")); WebElement source = driver.findElement(By.xpath("//li[@id='fourth']//a[contains(text(),'5000')]"));
WebElement target = driver.findElement(By.xpath("//ol[@id='amt7']//li[@class='placeholder']"));
// => HIGHLIGHT CẢ NGUỒN VÀ ĐÍCH TRƯỚC KHI KÉO
highlightElement(source); 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); highlightElement(target);
Thread.sleep(1500);
// Cách 1: Dùng hàm dragAndDrop() // --- 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(); actions.dragAndDrop(source, target).perform();
Thread.sleep(2000);
System.out.println("Da thuc hien keo tha");
// Kiểm tra kết quả kéo thả // --- 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')]")); WebElement result = driver.findElement(By.xpath("//ol[@id='amt7']//li[contains(text(),'5000')]"));
Assert.assertTrue(result.isDisplayed(), "Keo tha khong thanh cong!"); 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");
} }
} }
package com.automation.testcases; package com.automation.testcases;
import com.automation.base.BaseSetup;
import org.openqa.selenium.Alert; import org.openqa.selenium.Alert;
import org.openqa.selenium.By; import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.Assert; import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import java.time.Duration; public class HandleAlertTest extends BaseSetup {
import java.util.logging.Level;
import java.util.logging.Logger;
public class HandleAlertTest {
WebDriver driver;
@BeforeMethod
public void setUp() {
System.out.println(">>> [LOG] [" + java.time.LocalTime.now() + "] Bat dau khoi tao ChromeOptions...");
System.setProperty("webdriver.chrome.silentOutput", "true");
Logger.getLogger("org.openqa.selenium").setLevel(Level.SEVERE);
ChromeOptions options = new ChromeOptions();
options.addArguments("--no-sandbox");
options.addArguments("--disable-dev-shm-usage");
options.addArguments("--remote-allow-origins=*");
options.addArguments("--disable-logging");
options.addArguments("--log-level=3");
options.addArguments("--ignore-certificate-errors");
System.out.println(">>> [LOG] [" + java.time.LocalTime.now() + "] Dang goi: new ChromeDriver(options)...");
try {
driver = new ChromeDriver(options);
System.out.println(">>> [LOG] [" + java.time.LocalTime.now() + "] Mo trinh duyet thanh cong.");
} catch (Exception e) {
System.err.println(">>> [ERROR] Khong the khoi tao Driver: " + e.getMessage());
throw e;
}
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));
}
@Test(priority = 1, description = "Xử lý Alert cơ bản") @Test(priority = 1, description = "Bài 11: Xử lý Simple Alert (Thông báo đơn giản)")
public void testSimpleAlert() throws InterruptedException { public void testSimpleAlert() throws InterruptedException {
System.out.println(">>> [LOG] Truy cập trang thực hành Alert (Trang này rất ổn định)..."); System.out.println("\n========================================");
System.out.println(" BẮT ĐẦU TEST: Simple Alert");
System.out.println("========================================\n");
driver.get("https://the-internet.herokuapp.com/javascript_alerts"); driver.get("https://the-internet.herokuapp.com/javascript_alerts");
Thread.sleep(2000); Thread.sleep(2000);
System.out.println(">>> [LOG] Click button hiển thị Alert..."); // --- Bước 1: Tìm và highlight nút ---
driver.findElement(By.xpath("//button[text()='Click for JS Alert']")).click(); System.out.println("[Bước 1]: Tìm nút 'Click for JS Alert'. Đang tô viền đỏ...");
Thread.sleep(2000); 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();
Thread.sleep(1500);
// --- Bước 3: Xử lý Alert ---
Alert alert = driver.switchTo().alert(); Alert alert = driver.switchTo().alert();
System.out.println(">>> [LOG] Đã thấy Alert. Nội dung: " + alert.getText()); 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(); alert.accept();
System.out.println(">>> [LOG] Đã nhấn OK."); Thread.sleep(2000);
Thread.sleep(2000);
System.out.println(" ✓ Simple Alert xử lý thành công!\n");
} }
@Test(priority = 2, description = "Xử lý Confirm Alert (Dismiss)") @Test(priority = 2, description = "Bài 11: Xử lý Confirm Alert (Hộp thoại Có/Không)")
public void testConfirmAlert() throws InterruptedException { public void testConfirmAlert() throws InterruptedException {
System.out.println("\n========================================");
System.out.println(" BẮT ĐẦU TEST: Confirm Alert");
System.out.println("========================================\n");
driver.get("https://the-internet.herokuapp.com/javascript_alerts"); driver.get("https://the-internet.herokuapp.com/javascript_alerts");
Thread.sleep(2000); Thread.sleep(2000);
System.out.println(">>> [LOG] Click button hiển thị Confirm Alert..."); // --- Bước 1: Tìm và highlight nút Confirm ---
driver.findElement(By.xpath("//button[text()='Click for JS Confirm']")).click(); System.out.println("[Bước 1]: Tìm nút 'Click for JS Confirm'. Đang tô viền đỏ...");
Thread.sleep(2000); 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();
Thread.sleep(1500);
// --- Bước 3: Xử lý Alert ---
Alert alert = driver.switchTo().alert(); Alert alert = driver.switchTo().alert();
System.out.println(">>> [LOG] Đang nhấn Cancel (Dismiss)..."); 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(); alert.dismiss();
Thread.sleep(2000); Thread.sleep(2000);
String result = driver.findElement(By.id("result")).getText(); // --- Bước 5: Xác nhận kết quả ---
System.out.println(">>> [LOG] Kết quả: " + result); System.out.println("[Bước 5]: Tìm và highlight kết quả trả về...");
Assert.assertTrue(result.contains("Cancel")); 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!");
} }
@AfterMethod @Test(priority = 3, description = "Bài 11: Xử lý Prompt Alert (Hộp thoại nhập chữ)")
public void tearDown() { public void testPromptAlert() throws InterruptedException {
if (driver != null) { System.out.println("\n========================================");
driver.quit(); System.out.println(" BẮT ĐẦU TEST: Prompt Alert");
} 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();
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");
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ả!");
} }
} }
...@@ -10,21 +10,41 @@ import java.awt.event.KeyEvent; ...@@ -10,21 +10,41 @@ import java.awt.event.KeyEvent;
public class HandleRobotClassTest extends BaseSetup { public class HandleRobotClassTest extends BaseSetup {
@Test @Test(description = "Bài 13: Dùng Robot Class để điều khiển bàn phím cấp hệ điều hành")
public void testRobotClass() throws AWTException, InterruptedException { public void testRobotClass() throws AWTException, InterruptedException {
System.out.println("\n========================================");
System.out.println(" BẮT ĐẦU TEST: Bài 13 - Robot Class");
System.out.println("========================================\n");
driver.get("https://www.google.com"); driver.get("https://www.google.com");
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")); WebElement searchBox = driver.findElement(By.name("q"));
highlightElement(searchBox); 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"); searchBox.sendKeys("Selenium Java Robot Class");
Thread.sleep(2000);
// Example of using Robot class to press Enter
// --- 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!");
Robot robot = new Robot(); Robot robot = new Robot();
System.out.println(">>> Using Robot class to press ENTER...");
robot.keyPress(KeyEvent.VK_ENTER); robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER); robot.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(3000);
Thread.sleep(2000);
System.out.println(">>> Robot class test completed."); // --- 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("\n========================================");
System.out.println(" KẾT THÚC TEST: Robot Class hoạt động!");
System.out.println("========================================\n");
} }
} }
package com.automation.testcases; package com.automation.testcases;
import com.automation.base.BaseSetup;
import org.openqa.selenium.By; import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement; import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.Assert; import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import java.time.Duration;
import java.util.Set; import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
public class HandleWindowIFrameTest {
WebDriver driver;
@BeforeMethod
public void setUp() {
System.out.println(">>> [LOG] [" + java.time.LocalTime.now() + "] Bat dau khoi tao ChromeOptions...");
System.setProperty("webdriver.chrome.silentOutput", "true");
Logger.getLogger("org.openqa.selenium").setLevel(Level.SEVERE);
ChromeOptions options = new ChromeOptions();
options.addArguments("--no-sandbox");
options.addArguments("--disable-dev-shm-usage");
options.addArguments("--remote-allow-origins=*");
options.addArguments("--disable-logging");
options.addArguments("--log-level=3");
options.addArguments("--ignore-certificate-errors");
System.out.println(">>> [LOG] [" + java.time.LocalTime.now() + "] Dang goi: new ChromeDriver(options)...");
try {
driver = new ChromeDriver(options);
System.out.println(">>> [LOG] [" + java.time.LocalTime.now() + "] Mo trinh duyet thanh cong.");
} catch (Exception e) {
System.err.println(">>> [ERROR] Khong the khoi tao Driver: " + e.getMessage());
throw e;
}
driver.manage().window().maximize(); public class HandleWindowIFrameTest extends BaseSetup {
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));
}
@Test(priority = 1, description = "Xử lý chuyển đổi Windows (Tab)") @Test(priority = 1, description = "Bài 12: Xử lý chuyển đổi giữa nhiều Tab (Windows)")
public void testHandleWindows() throws InterruptedException { public void testHandleWindows() throws InterruptedException {
System.out.println(">>> [LOG] Truy cập trang thực hành Windows..."); System.out.println("\n========================================");
System.out.println(" BẮT ĐẦU TEST: Xử lý Tab/Windows");
System.out.println("========================================\n");
driver.get("https://the-internet.herokuapp.com/windows"); driver.get("https://the-internet.herokuapp.com/windows");
Thread.sleep(2000); Thread.sleep(2000);
// --- Bước 1: Ghi nhớ handle của Tab hiện tại ---
String mainWindowHandle = driver.getWindowHandle(); String mainWindowHandle = driver.getWindowHandle();
System.out.println(">>> [LOG] Window chính: " + mainWindowHandle); System.out.println("[Bước 1]: Đang ở Tab chính. Handle: " + mainWindowHandle.substring(0, 8) + "...");
System.out.println(">>> [LOG] Click 'Click Here' để mở Tab mới..."); // --- Bước 2: Click để mở Tab mới ---
driver.findElement(By.linkText("Click Here")).click(); System.out.println("[Bước 2]: Tìm và highlight link 'Click Here'. Chuẩn bị click mở Tab mới...");
Thread.sleep(4000); 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(); Set<String> allWindowHandles = driver.getWindowHandles();
System.out.println(" ✓ Tổng số Tab đang mở: " + allWindowHandles.size());
for (String handle : allWindowHandles) { for (String handle : allWindowHandles) {
if (!handle.equals(mainWindowHandle)) { if (!handle.equals(mainWindowHandle)) {
System.out.println(">>> [LOG] Đang chuyển sang Tab mới...");
driver.switchTo().window(handle); driver.switchTo().window(handle);
Thread.sleep(2000); Thread.sleep(2000);
System.out.println("[Bước 4]: Đã chuyển sang Tab mới. Tiêu đề: '" + driver.getTitle() + "'");
break; break;
} }
} }
System.out.println(">>> [LOG] Tiêu đề trang mới: " + driver.getTitle()); // --- Bước 5: Đóng Tab mới và quay về ---
driver.close(); System.out.println("[Bước 5]: Đóng Tab mới và quay trở về Tab chính...");
driver.close();
System.out.println(">>> [LOG] Đã đóng Tab. Quay lại Window chính...");
driver.switchTo().window(mainWindowHandle); driver.switchTo().window(mainWindowHandle);
Thread.sleep(2000); Thread.sleep(2000);
System.out.println(" ✓ Đã quay về Tab chính: '" + driver.getTitle() + "'");
Assert.assertTrue(driver.getTitle().contains("The Internet"));
Assert.assertTrue(driver.getTitle().contains("The Internet"), "Không quay về được Tab chính!");
} }
@Test(priority = 2, description = "Xử lý iFrame") @Test(priority = 2, description = "Bài 12: Xử lý iFrame (Trang web bên trong trang web)")
public void testHandleIFrame() throws InterruptedException { public void testHandleIFrame() throws InterruptedException {
System.out.println(">>> [LOG] Truy cập trang thực hành iFrame..."); System.out.println("\n========================================");
System.out.println(" BẮT ĐẦU TEST: Xử lý iFrame");
System.out.println("========================================\n");
driver.get("https://the-internet.herokuapp.com/iframe"); driver.get("https://the-internet.herokuapp.com/iframe");
Thread.sleep(3000); Thread.sleep(3000);
System.out.println(">>> [LOG] Đang chuyển vào iFrame mce_0_ifr..."); // --- 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);
// --- 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"); driver.switchTo().frame("mce_0_ifr");
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")); WebElement editor = driver.findElement(By.id("tinymce"));
System.out.println(">>> [LOG] Đã ở TRONG iFrame. Đang xóa text bằng JS...");
// Sử dụng Javascript để clear và set text cho ổn định với TinyMCE
org.openqa.selenium.JavascriptExecutor js = (org.openqa.selenium.JavascriptExecutor) driver; org.openqa.selenium.JavascriptExecutor js = (org.openqa.selenium.JavascriptExecutor) driver;
js.executeScript("arguments[0].innerHTML = '';", editor); js.executeScript("arguments[0].innerHTML = '';", editor);
Thread.sleep(1000); Thread.sleep(1000);
System.out.println(">>> [LOG] Đang nhập text mới..."); System.out.println("[Bước 4]: Nhập nội dung mới vào ô soạn thảo...");
editor.sendKeys("Chào Anh Tester - Học Selenium Java!"); editor.sendKeys("Xin chào từ Anh Tester - Học Selenium Java!");
Thread.sleep(2000); 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(); driver.switchTo().defaultContent();
System.out.println(">>> [LOG] Đã thoát ra ngoài iFrame."); Thread.sleep(1500);
Thread.sleep(2000); System.out.println(" ✓ Đã thoát ra ngoài iFrame thành công!");
String headerText = driver.findElement(By.tagName("h3")).getText();
Assert.assertTrue(headerText.contains("An iFrame"));
}
@AfterMethod WebElement headerText = driver.findElement(By.tagName("h3"));
public void tearDown() { Assert.assertTrue(headerText.getText().contains("An iFrame"), "Không thoát được khỏi iFrame!");
if (driver != null) {
driver.quit();
}
} }
} }
package com.automation.testcases; package com.automation.testcases;
import com.automation.base.BaseSetup;
import org.openqa.selenium.By; import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement; import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterMethod; import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import java.time.Duration; import java.time.Duration;
public class WebElementCommandsTest { public class WebElementCommandsTest extends BaseSetup {
WebDriver driver; @Test(description = "Bài 9: Các lệnh tương tác với WebElement")
@BeforeMethod
public void setUp() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--no-sandbox");
options.addArguments("--disable-dev-shm-usage");
options.addArguments("--remote-allow-origins=*");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
// Cài đặt chờ ngầm định 10s cho việc tìm kiếm element
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
}
@Test
public void testFindAndInteractWithElements() throws InterruptedException { public void testFindAndInteractWithElements() throws InterruptedException {
// Mở trang CRM demo của Anh Tester System.out.println("\n========================================");
driver.get("https://crm.anhtester.com/admin/authentication"); System.out.println(" BẮT ĐẦU TEST: Bài 9 - WebElement Commands");
System.out.println("Đã mở trang đăng nhập CRM"); System.out.println("========================================\n");
driver.get("https://cms.anhtester.com/login");
Thread.sleep(2000);
// 1. CHUẨN MỰC: TÌM ELEMENT VÀ TƯƠNG TÁC (Check Locator) // --- Bước 1: Tìm và highlight ô Email ---
// Tìm ô Email qua ID và điền chữ 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")); WebElement inputEmail = driver.findElement(By.id("email"));
highlightElement(inputEmail);
inputEmail.clear(); 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"); inputEmail.sendKeys("admin@example.com");
Thread.sleep(1500);
// Tìm ô Password qua ID và điền chữ // --- 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")); WebElement inputPassword = driver.findElement(By.id("password"));
highlightElement(inputPassword);
inputPassword.clear(); inputPassword.clear();
inputPassword.sendKeys("123456");
Thread.sleep(2000); // Tạm dừng 2s để bạn nhìn thấy chữ được điền vào // --- 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);
// 2. NÂNG CAO: DÙNG EXPLICIT WAIT (Chờ đợi thông minh) // --- Bước 5: Dùng Explicit Wait để chờ nút Login sẵn sàng ---
// Đợi cho đến khi nút Login sẵn sàng để click (tối đa đợi 10s) 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)); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement buttonLogin = wait WebElement loginBtn = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@type='submit']")));
.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@type='submit']")));
// 3. NÂNG CAO: DÙNG JAVASCRIPT ĐỂ CLICK NGẦM (Xử lý khi bị che khuất) // --- Bước 6: Highlight và Click nút Login ---
// Thông thường bạn chỉ cần gõ: buttonLogin.click(); System.out.println("[Bước 6]: Tìm thấy nút Login! Đang tô viền đỏ...");
// Nhưng ở đây ta dùng thử JS để click xuyên qua mọi chướng ngại vật highlightElement(loginBtn);
System.out.println("Thực hiện click nút Login bằng JavascriptExecutor..."); Thread.sleep(1500);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", buttonLogin);
Thread.sleep(3000); // Chờ 3s để bạn quan sát kết quả trang sau khi bấm Đăng nhập 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);
Thread.sleep(3000);
System.out.println("Thực thi kịch bản thành công!"); // --- 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!");
@AfterMethod System.out.println("\n========================================");
public void tearDown() { System.out.println(" KẾT THÚC TEST: Login thành công!");
if (driver != null) { System.out.println("========================================\n");
driver.quit(); // Đóng trình duyệt dọn dẹp RAM
}
} }
} }
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