NỘI DUNG BÀI HỌC

Thực hành Page Object Model (part 1)



Website thực hành: https://crm.anhtester.com/admin/authentication

Email: admin@example.com
Password: 123456

✅ Tạo Page Object với trang Customers

[Selenium Java] Bài 20: Thực hành Page Object Model (part 1) | Anh Tester

✅ Viết Auto Test chức năng Add New Customer

[Selenium Java] Bài 20: Thực hành Page Object Model (part 1) | Anh Tester
[Selenium Java] Bài 20: Thực hành Page Object Model (part 1) | Anh Tester

✅ Code tham khảo Page Object Model

🔆 CommonPage

package com.anhtester.Bai20_ThucHanhPageObject.pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class CommonPage {

    private WebDriver driver;

    public CommonPage(WebDriver driver){
        this.driver = driver;
    }

    public By menuDashboard = By.xpath("//span[normalize-space()='Dashboard']");
    public By menuCustomers = By.xpath("//span[normalize-space()='Customers']");
    public By menuSales = By.xpath("//li[@class='menu-item-sales']");
    public By menuProjects = By.xpath("//span[normalize-space()='Projects']");
    public By itemNotifications = By.xpath("//a[contains(@class,'notifications-icon')]");

    public DashboardPage clickMenuDashboard(){
        driver.findElement(menuDashboard).click();

        return new DashboardPage(driver);
    }

    public CustomerPage clickMenuCustomer(){
        driver.findElement(menuCustomers).click();

        return new CustomerPage(driver);
    }

}


🔆 LoginPage

package com.anhtester.Bai20_ThucHanhPageObject.pages;

import com.anhtester.constants.ConfigData;
import com.anhtester.keywords.WebUI;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;

public class LoginPage extends CommonPage {
    //Khai báo driver cục bộ
    private WebDriver driver;
    private String URL = "https://crm.anhtester.com/admin/authentication";

    //Hàm xây dựng cho từng class Page
    public LoginPage(WebDriver driver) {
        super(driver);
        this.driver = driver;
    }

    //Khai báo các element dạng đối tượng By
    private By headerPage = By.xpath("//h1[normalize-space()='Login']");
    private By inputEmail = By.xpath("//input[@id='email']");
    private By inputPassword = By.xpath("//input[@id='password']");
    private By buttonLogin = By.xpath("//button[normalize-space()='Login']");
    private By errorMessage = By.xpath("//div[contains(@class,'alert alert-danger')]");

    private By menuDashboard = By.xpath("//span[normalize-space()='Dashboard']");

    //Khai báo các hàm xử lý thuộc trang Login
    public void enterEmail(String email){
        driver.findElement(inputEmail).sendKeys(email);
    }

    public void enterPassword(String password){
        driver.findElement(inputPassword).sendKeys(password);
    }

    public void clickLoginButton(){
        driver.findElement(buttonLogin).click();
    }

    public DashboardPage loginCRM(String email, String password) {
        driver.get(ConfigData.URL);
        enterEmail(email);
        enterPassword(password);
        clickLoginButton();

        return new DashboardPage(driver);
    }

    public void verifyLoginSuccess() {
        WebUI.waitForPageLoaded(driver);
        Assert.assertTrue(driver.findElement(menuDashboard).isDisplayed(), "FAIL. Can not redirect to Dashboard page.");
        Assert.assertEquals(driver.getCurrentUrl(), "https://crm.anhtester.com/admin/", "FAIL. The current url not match.");
    }

    public void verifyLoginFail(String expectedMessage) {
        WebUI.waitForPageLoaded(driver);
        Assert.assertTrue(WebUI.checkElementExist(driver, errorMessage), "FAIL. The error message not display.");
        Assert.assertEquals(driver.findElement(errorMessage).getText(), expectedMessage, "FAIL. The content of error massge not match.");
    }
}

 

🔆 DashboardPage

package com.anhtester.Bai20_ThucHanhPageObject.pages;

import com.anhtester.keywords.WebUI;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;

public class DashboardPage extends CommonPage {
    private WebDriver driver;

    public DashboardPage(WebDriver driver) {
        super(driver);
        this.driver = driver;
    }

    private By buttonDashboardOptions = By.xpath("//div[normalize-space()='Dashboard Options']");
    private By totalInvoicesAwaitingPayment = By.xpath("(//span[normalize-space()='Invoices Awaiting Payment']/parent::div)/following-sibling::span");
    private By totalConvertedLeads = By.xpath("(//span[normalize-space()='Converted Leads']/parent::div)/following-sibling::span");
    private By totalProjectsInProgress = By.xpath("(//span[normalize-space()='Projects In Progress']/parent::div)/following-sibling::span");
    private By totalTasksNotFinished = By.xpath("(//span[normalize-space()='Tasks Not Finished']/parent::div)/following-sibling::span");
    private By checkboxQuickStatistics = By.xpath("//input[@id='widget_option_top_stats']");
    private By sectionQuickStatistics = By.xpath("//div[@id='widget-top_stats']");

    public void clickButtonDashboardOptions(){
        WebUI.waitForPageLoaded(driver);
        System.out.println(WebUI.checkElementExist(driver, buttonDashboardOptions));
        driver.findElement(buttonDashboardOptions).click();
    }

    public void verifyCheckboxQuickStatistics(){
        WebUI.sleep(1);
        Assert.assertTrue(driver.findElement(checkboxQuickStatistics).isSelected(), "FAIL!! The value of checkbox Quick Statistics not match.");
        Assert.assertTrue(driver.findElement(sectionQuickStatistics).isDisplayed(), "FAI!! The section Quick Statistics not display.");
    }

    public void checkTotalInvoicesAwaitingPayment(String value) {
        WebUI.waitForPageLoaded(driver);
        Assert.assertTrue(WebUI.checkElementExist(driver, totalInvoicesAwaitingPayment), "The section Invoices Awaiting Payment not display.");
        Assert.assertEquals(driver.findElement(totalInvoicesAwaitingPayment).getText(), value, "FAIL!! Invoices Awaiting Payment total not match.");
    }

    public void checkTotalConvertedLeads() {
        WebUI.waitForPageLoaded(driver);
        Assert.assertTrue(WebUI.checkElementExist(driver, totalConvertedLeads), "The section Converted Leads not display.");
        Assert.assertEquals(driver.findElement(totalConvertedLeads).getText(), "1 / 5", "FAIL!! Converted Leads total not match.");
    }

    public void checkTotalProjectsInProgress() {
        WebUI.waitForPageLoaded(driver);
        Assert.assertTrue(WebUI.checkElementExist(driver, totalProjectsInProgress), "The section Projects In Progress not display.");
        Assert.assertEquals(driver.findElement(totalProjectsInProgress).getText(), "4 / 4", "FAIL!! Projects In Progress total not match.");
    }

    public void checkTotalTasksNotFinished() {
        WebUI.waitForPageLoaded(driver);
        Assert.assertTrue(WebUI.checkElementExist(driver, totalTasksNotFinished), "The section Tasks Not Finished not display.");
        Assert.assertEquals(driver.findElement(totalTasksNotFinished).getText(), "8 / 8", "FAIL!! Tasks Not Finished total not match.");
    }
}


🔆 CustomerPage

package com.anhtester.Bai20_ThucHanhPageObject.pages;

import com.anhtester.keywords.WebUI;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;

public class CustomerPage extends CommonPage {
    private WebDriver driver;

    public CustomerPage(WebDriver driver) {
        super(driver);
        this.driver = driver;
        new WebUI(driver);
    }

    //Elements
    private By buttonAddNewCustomer = By.xpath("//a[normalize-space()='New Customer']");
    private By headerPage = By.xpath("//span[normalize-space()='Customers Summary']");
    private By inputSearchCustomer = By.xpath("//div[@id='clients_filter']//input[@placeholder='Search...']");
    private By firstItemCustomerName = By.xpath("//tbody/tr[1]/td[3]/a");
    private By inputCompany = By.xpath("//input[@id='company']");
    private By inputVat = By.xpath("//input[@id='vat']");
    private By inputPhone = By.xpath("//input[@id='phonenumber']");
    private By inputWebsite = By.xpath("//input[@id='website']");
    private By selectGroups = By.xpath("//button[@data-id='groups_in[]']");
    private By inputGroups = By.xpath("//button[@data-id='groups_in[]']/following-sibling::div//input");
    private By selectLanguage = By.xpath("//button[@data-id='default_language']");
    private By itemVietnam = By.xpath("//span[normalize-space()='Vietnamese']");
    private By inputAddress = By.xpath("//textarea[@id='address']");
    private By inputCity = By.xpath("//input[@id='city']");
    private By inputState = By.xpath("//input[@id='state']");
    private By inputZip = By.xpath("//input[@id='zip']");
    private By selectCountry = By.xpath("//button[@data-id='country']");
    private By inputCountry = By.xpath("//button[@data-id='country']/following-sibling::div//input");
    private By buttonSave = By.xpath("//div[@id='profile-save-section']//button[normalize-space()='Save']");
    private By alertMessage = By.xpath("//span[@class='alert-title']");


    //Hàm xử lý cho trang Customer
    public void clickAddNewButton() {
        WebUI.clickElement(buttonAddNewCustomer);
    }

    public void selectLanguage(String languageName) {
        WebUI.clickElement(selectLanguage);
        WebUI.clickElement(By.xpath("//span[normalize-space()='" + languageName + "']"));
    }

    public void enterDataAddNewCustomer(String customerName) {
        WebUI.setText(inputCompany, customerName);
        WebUI.setText(inputVat, "10");
        WebUI.setText(inputPhone, "123456");
        WebUI.setText(inputWebsite, "https://anhtester.com");
        WebUI.clickElement(selectGroups);
        WebUI.sleep(1);
        WebUI.setText(inputGroups, "VIP");
        WebUI.sleep(1);
        WebUI.setKey(inputGroups, Keys.ENTER);
        WebUI.sleep(1);
        WebUI.clickElement(selectGroups);
        selectLanguage("Vietnamese");
        WebUI.sleep(1);

        WebUI.setText(inputAddress, "Can Tho");
        WebUI.setText(inputCity, "Can Tho");
        WebUI.setText(inputState, "Can Tho");
        WebUI.setText(inputZip, "12345");

        WebUI.clickElement(selectCountry);
        WebUI.sleep(1);
        WebUI.setText(inputCountry, "Vietnam");
        WebUI.sleep(1);
        WebUI.setKey(selectCountry, Keys.ENTER);
        WebUI.sleep(1);
        WebUI.clickElement(buttonSave);
        WebUI.sleep(2);
        Assert.assertTrue(WebUI.checkElementExist(driver, alertMessage), "\uD83D\uDC1E FAIL!! The alert message success not display.");
        Assert.assertEquals(driver.findElement(alertMessage).getText().trim(), "Customer added successfully.", "\uD83D\uDC1E FAIL!! The content of alert message not match.");
    }

    public void checkCustomerDetail(String customerName) {
        WebUI.waitForPageLoaded(driver);
        WebUI.clickElement(menuCustomers);
        WebUI.waitForPageLoaded(driver);
        WebUI.setText(inputSearchCustomer, customerName);
        WebUI.waitForPageLoaded(driver);
        WebUI.sleep(2);
        Assert.assertTrue(WebUI.checkElementExist(driver, firstItemCustomerName), "\uD83D\uDC1E FAIL!! The customer name not display in table.");
        Assert.assertEquals(driver.findElement(firstItemCustomerName).getText(), customerName, "\uD83D\uDC1E FAILL!! The customer name not match.");
    }
}

 

🔆 CustomerTest

package com.anhtester.Bai20_ThucHanhPageObject.testcases;

import com.anhtester.Bai20_ThucHanhPageObject.pages.CustomerPage;
import com.anhtester.Bai20_ThucHanhPageObject.pages.DashboardPage;
import com.anhtester.Bai20_ThucHanhPageObject.pages.LoginPage;
import com.anhtester.common.BaseTest;
import org.testng.annotations.Test;

public class CustomerTest extends BaseTest {

    LoginPage loginPage;
    DashboardPage dashboardPage;
    CustomerPage customerPage;

    @Test
    public void testAddNewCustomer(){
        loginPage = new LoginPage(driver);
        dashboardPage = loginPage.loginCRM("admin@example.com", "123456");

        customerPage = dashboardPage.clickMenuCustomer(); //Hàm này nằm bên CommonPage

        customerPage.clickAddNewButton();
        customerPage.enterDataAddNewCustomer("Anh Tester 07062024A3");
        customerPage.checkCustomerDetail("Anh Tester 07062024A4");
    }
}


Viết tiếp đoạn verify kết quả Customer Detail và check customer bên trang Project ở phần 2 nhé.

Teacher

Teacher

Anh Tester

Software Quality Engineer

Đường dẫu khó chân vẫn cần bước đi
Đời dẫu khổ tâm vẫn cần nghĩ thấu

Cộng đồng Automation Testing Việt Nam:

🌱 Telegram Automation Testing:   Cộng đồng Automation Testing
🌱 
Facebook Group Automation: Cộng đồng Automation Testing Việt Nam
🌱 
Facebook Fanpage: Cộng đồng Automation Testing Việt Nam - Selenium
🌱 Telegram
Manual Testing:   Cộng đồng Manual Testing
🌱 
Facebook Group Manual: Cộng đồng Manual Testing Việt Nam

Chia sẻ khóa học lên trang

Bạn có thể đăng khóa học của chính bạn lên trang Anh Tester để kiếm tiền

Danh sách bài học