Learn how to use Selenium Web Driver
Bài đăng này đã không được cập nhật trong 3 năm
1. Overview
1.1. Introduction to Selenium
Homepage: http://www.seleniumhq.org/
Selenium is an open source tool for automation testing of web based applications. Test cases in selenium can be written in HTML or many other popular programming languages supported by selenium like Java, C#, Ruby, Python etc.
1.2 Selenium has a suite of tools and one of them is Selenium Web Driver
2. Download and install
2.1. Download & Install JDK (Java Development Kit)
Link: http://www.oracle.com/technetwork/java/javase/downloads/index.html
2.2. Download Eclipse
Link: https://www.eclipse.org/downloads/
2.3. Download WebDriver Java Client
2.4. Configuration Eclipse With Selenium Driver
2.4.1. Select WorkSpace on Eclipse start up
2.4.2. Create a new Project
Step 1: File > New > Java Project
Step 2: Input Project Name > Finish
2.4.3. Create a new Package
Step 1: File > New > Package
Step 2: Input Name > Finish
2.4.4. Create a new Class
Step 1: Select Package > Right click > New > Class
Step 2: Input Name > Click on "public static void main..." > Finish
2.4.5. Add External Jars to Java build path
Step 1: Right click Project > Properties
Step 2: Click Add External JARs > select *.jar files in folder downloaded in "2.3. Download WebDriver Java Client"
After all configuration has been completed, the screen will display as below.
2.5. Data Driven with Excel
2.5.1. Download Apache POI
Link: http://poi.apache.org/
2.5.2. Add Apache POI
Step 1: Right click the project name, navigate to Build Path and select “Configure Build Path”.
Step 2: Click Add External JARs and select *.jar files in [poi-3.11-beta2] folder /[ooxml-lib]folder/[lib]folder
3. Demo
3.1: Create testcase for Login function
Demo: Create 5 TCs for login function of website: http://amazon247.vn
- Test case 1 : Login without email and password (blank)
- Test case 2: Login without email (blank) and an invalid password
- Test case 3: Login with an invalid email and without password (blank)
- Test case 4: Login with invalid email and password
- Test case 5: Login with valid email and password
Step 1: Create a ‘New Package‘ file and name it as ‘testData’, by right click on the Project and select New > Package. Place all of your test data in this folder (package) whether it is a sql file, excel file or anything.
Step 2: Place a Excel file in the above created package location and save it as TestData.xlsx. Fill the data in the excel like below image:
Step 3: Create 'utility' package
Step 4: Add two constant variables (testData package path & Excel file name) in the Constant class.
package utility;
public class constant {
// TODO Auto-generated method stub
public static final String URL1 = "http://amazon247.vn";
public static final String Path_TestData = "D://folder_eclip//demoSeleniumDriver//src//testData//";
public static final String File_TestData = "TestData.xlsx";
}
Step 5: Create a ‘New Class‘ file, by right click on the ‘utility‘ Package and select New > Class and name it as ‘ExcelUtils‘. First we will write basic read/write methods.
package utility;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.bcel.classfile.Constant;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelUtils { private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell Cell;
private static XSSFRow Row;
//This method is to set the File path and to open the Excel file, Pass Excel Path and Sheetname as Arguments to this method
public static void setExcelFile(String Path,String SheetName) throws Exception {
try {
// Open the Excel file
FileInputStream ExcelFile = new FileInputStream(Path);
// Access the required test data sheet
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
} catch (Exception e){
throw (e);
}
}
//This method is to read the test data from the Excel cell, in this we are passing parameters as Row num and Col num
public static String getCellData(int RowNum, int ColNum) throws Exception{
try{
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
String CellData = Cell.getStringCellValue();
return CellData;
}catch (Exception e){
return"";
}
}
//This method is to write in the Excel cell, Row num and Col num are the parameters
public static void setCellData(String Result, int RowNum, int ColNum) throws Exception {
try{
Row = ExcelWSheet.getRow(RowNum);
Cell = Row.getCell(ColNum, Row.RETURN_BLANK_AS_NULL);
if (Cell == null) {
Cell = Row.createCell(ColNum);
Cell.setCellValue(Result);
} else {
Cell.setCellValue(Result);
}
// Constant variables Test Data path and Test Data file name
FileOutputStream fileOut = new FileOutputStream(constant.Path_TestData + constant.File_TestData);
ExcelWBook.write(fileOut);
fileOut.flush();
fileOut.close();
}catch(Exception e){
throw (e);
}
}
}
Step 6: In demoSeleniumDriver package create "DangNhap" class
package demoSeleniumDriver;
import java.util.concurrent.TimeUnit;
import junit.framework.Assert;
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.firefox.FirefoxDriver;
import pageObjects.*;
import utility.constant;
// Import Package utility.*
import utility.ExcelUtils;
import appModules.SignIn_Action;
public class DangNhap {
private static WebDriver driver = null;
public static void main(String[] args) throws Exception {
//This is to open the Excel file. Excel path, file name and the sheet name are parameters to this method
ExcelUtils.setExcelFile(constant.Path_TestData + constant.File_TestData,"Sheet1");
//driver = new FirefoxDriver();
System.setProperty("webdriver.chrome.driver", "D://chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(constant.URL1);
driver.findElement(By.xpath(".//*[@id='loginBar']")).click();
//nhap voi lenh switch for (int i = 1; i <=5; i++) {
switch(i){
// Log in with email ad pass blank
case 1:
{
String sUserName = ExcelUtils.getCellData(1, 1);
String sPassword = ExcelUtils.getCellData(1, 2);
driver.findElement(By.name("email")).sendKeys(sUserName);
driver.findElement(By.name("password")).sendKeys(sPassword);
driver.findElement(By.xpath(".//*[@id='frmLogin']/button")).click();
String str = driver.findElement(By.xpath(".//*[@id='email-error']")).getText();
String str1 = driver.findElement(By.xpath(".//*[@id='password-error']")).getText();
if(str.equals("Vui lòng nhập Email.") == true && str1.equals("Vui lòng nhập mật khẩu.") == true ){
System.out.println("Please enter your email and password.");
ExcelUtils.setCellData("Pass", 1, 3);
//Thread.sleep(3000);
}
else
{
System.out.println("Message of testcase email , password display wrong");
ExcelUtils.setCellData("Fail", 1, 3);
} driver.navigate().refresh();
Thread.sleep(1000);
break;
}
//log in vith email blank
case 2:
{
driver.findElement(By.xpath(".//*[@id='loginBar']")).click();
String sUserName = ExcelUtils.getCellData(2, 1);
String sPassword = ExcelUtils.getCellData(2, 2);
driver.findElement(By.name("email")).sendKeys(sUserName);
driver.findElement(By.name("password")).sendKeys(sPassword);
driver.findElement(By.xpath(".//*[@id='frmLogin']/button")).click();
String str = driver.findElement(By.xpath(".//*[@id='email-error']")).getText();
if(str.equals("Vui lòng nhập Email.") == true ){
System.out.println("Please enter your email.");
ExcelUtils.setCellData("Pass", 2, 3);
//Thread.sleep(3000);
}
else
{
System.out.println("Message testcase2 display wrong");
ExcelUtils.setCellData("Fail", 2, 3);
//Thread.sleep(3000);
}
driver.navigate().refresh();
Thread.sleep(1000);
break;
}
//log in with pwd blank
case 3:
{
driver.findElement(By.xpath(".//*[@id='loginBar']")).click();
String sUserName = ExcelUtils.getCellData(3, 1);
String sPassword = ExcelUtils.getCellData(3, 2);
driver.findElement(By.name("email")).sendKeys(sUserName);
driver.findElement(By.name("password")).sendKeys(sPassword);
driver.findElement(By.xpath(".//*[@id='frmLogin']/button")).click();
String str = driver.findElement(By.xpath(".//*[@id='password-error']")).getText();
if(str.equals("Vui lòng nhập mật khẩu.") == true ){
System.out.println("Please enter your password.");
ExcelUtils.setCellData("Pass", 3, 3);
//Thread.sleep(3000);
}
else
{
System.out.println("Message of testcase not enter password display wrong");
ExcelUtils.setCellData("Fail", 3, 3);
//Thread.sleep(3000);
}
driver.navigate().refresh();
Thread.sleep(1000);
break;
}
//log in with email and pass invalid
case 4:
{
driver.findElement(By.xpath(".//*[@id='loginBar']")).click();
String sUserName = ExcelUtils.getCellData(4, 1);
String sPassword = ExcelUtils.getCellData(4, 2);
driver.findElement(By.name("email")).sendKeys(sUserName);
driver.findElement(By.name("password")).sendKeys(sPassword);
driver.findElement(By.xpath(".//*[@id='frmLogin']/button")).click();
String str = driver.findElement(By.xpath(".//*[@id='email-error']")).getText();
if(str.equals("Vui lòng nhập đúng định dạng email. Ví dụ : support@amazon247.vn.") == true){
System.out.println("Please enter your email and password valid.");
ExcelUtils.setCellData("Pass", 4, 3);
//Thread.sleep(3000);
}
else
{
System.out.println("Message of testcase eneter email and pwd invalid display wrong");
ExcelUtils.setCellData("Fail", 4, 3);
//Thread.sleep(3000);
}
driver.navigate().refresh();
Thread.sleep(1000);
break;
}
//log in with email and pass valid
case 5:
{
driver.findElement(By.xpath(".//*[@id='loginBar']")).click();
String sUserName = ExcelUtils.getCellData(5, 1);
String sPassword = ExcelUtils.getCellData(5, 2);
driver.findElement(By.name("email")).sendKeys(sUserName);
driver.findElement(By.name("password")).sendKeys(sPassword);
driver.findElement(By.xpath(".//*[@id='frmLogin']/button")).click();
String str =driver.findElement(By.xpath(".//*[@id='loginBar']")).getText();
if(str.equals("Xin chào Hiến") == true){ System.out.println("Login success");
ExcelUtils.setCellData("Pass", 5, 3);
}
else
{
System.out.println("Message of testcase enter email and pwd valid display wrong");
ExcelUtils.setCellData("Fail", 5, 3);
}
break;
}
default: System.out.println("Khong vao cac truong hop tren ");
break;
}
}
driver.findElement(By.id("loginBar")).click();
driver.findElement(By.xpath(".//*[@id='userFunction']/a[6]")).click();
driver.quit();
}
}
Steps 7: Run DangNhap.java.Once it finished open the Excel file and check for the result.
3.2: Create testcase for Search function
Demo: Create 5 TCs for Search function of website: http://www.store.demoqa.com
- Test case 1 : Search with without keyword (blank)
- Test case 2: Search with invalid keyword
- Test case 3: Search with valid keyword
Step 1: In testData package create and save TestData1.xlsx. Fill the data in the excel like below image:
Step 2: In ExcelUtils class add setCellData1 method
public static void setCellData1(String Result, int RowNum, int ColNum) throws Exception {
try{
Row = ExcelWSheet.getRow(RowNum);
Cell = Row.getCell(ColNum, Row.RETURN_BLANK_AS_NULL);
if (Cell == null) {
Cell = Row.createCell(ColNum);
Cell.setCellValue(Result);
} else {
Cell.setCellValue(Result);
}
// Constant variables Test Data path and Test Data file name
FileOutputStream fileOut = new FileOutputStream(constant.Path_TestData1 + constant.File_TestData1);
ExcelWBook.write(fileOut);
fileOut.flush();
fileOut.close();
}catch(Exception e){
throw (e);
} }
Step 3: In constant class add URL = "http://www.store.demoqa.com"
public static final String URL = "http://www.store.demoqa.com"
Step 4: In demoSeleniumDriver package create "Search" class
package demoSeleniumDriver;
import java.util.concurrent.TimeUnit;
import junit.framework.Assert;
import org.apache.http.util.Asserts;
import org.hamcrest.core.Is;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import pageObjects.*; import utility.constant;
// Import Package utility.*
import utility.ExcelUtils;
public class Search {
private static WebDriver driver = null;
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//driver = new FirefoxDriver();
System.setProperty("webdriver.chrome.driver", "D://chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
ExcelUtils.setExcelFile(constant.Path_TestData1 + constant.File_TestData1,"Sheet1");
// open URL http://amazon247.vn
driver.get(constant.URL);
//nhap voi lenh switch
for (int i = 1; i <=5; i++) {
switch(i){
case 1:
{
String sKey = ExcelUtils.getCellData(1, 1);
driver.findElement(By.xpath(".//*[@id='main-nav']/form/fieldset/input[1]")).sendKeys(sKey);
driver.findElement(By.xpath(".//*[@id='main-nav']/form/fieldset/input[1]")).sendKeys(Keys.ENTER);
Thread.sleep(5000);
String str = driver.findElement(By.xpath(".//*[@id='technicalProductFeaturesATF']/ul/li[1]")).getText();
if(str.equalsIgnoreCase("Full HD AH-IPS LED display with 178° wide-view angle in frameless design for edge-to-edge brilliance") == true){
System.out.println("Khong co ket qua tim kiem");
ExcelUtils.setCellData1("Pass", 1, 2);
}
else
{
System.out.println("hien thi ket qua search khi khong nhap data");
ExcelUtils.setCellData1("Fail", 1, 2);
}
// driver.navigate().refresh();
Thread.sleep(1000);
break;
}
case 2:
{
String sKey = ExcelUtils.getCellData(2, 1);
driver.findElement(By.xpath(".//*[@id='main-nav']/form/fieldset/input[1]")).sendKeys(sKey);
driver.findElement(By.xpath(".//*[@id='main-nav']/form/fieldset/input[1]")).sendKeys(Keys.ENTER);
Thread.sleep(5000);
String str = driver.findElement(By.xpath(".//*[@id='content']")).getText();
if(str.equals("Sorry, but nothing matched your search criteria. Please try again with some different keywords.") == true ){
System.out.println("Please enter again, did not match any products.");
ExcelUtils.setCellData1("Pass", 2, 2);
}
else
{
System.out.println("display result diffrent keyword");
ExcelUtils.setCellData1("Fail", 2, 2);
}
driver.navigate().to("http://www.store.demoqa.com");
break;
}
case 3:
{
String sKey = ExcelUtils.getCellData(3, 1);
driver.findElement(By.xpath(".//*[@id='main-nav']/form/fieldset/input[1]")).sendKeys(sKey);
driver.findElement(By.xpath(".//*[@id='main-nav']/form/fieldset/input[1]")).sendKeys(Keys.ENTER);
Thread.sleep(20000);
String str = driver.findElement(By.xpath(".//*[@id='main-nav']/form/fieldset/input[1]")).getText();
int osize = driver.findElements(By.className("item_image")).size();
if(osize >= 1){
System.out.println("so ket qua tim kiem Iphone = " + osize);
ExcelUtils.setCellData1("Pass", 3, 2);
}
else
{
System.out.println("display result wrong ");
ExcelUtils.setCellData1("Fail", 3, 2);
}
break;
}
}
}
} }
Step 5: Run Search class .Once it finished open the TestData1.xlsx file and check for the result.
Video illustration Login funtion and Search function
https://www.youtube.com/watch?v=evaXggNZFeI&feature=youtu.be
3.3 : Create test case login function and show actual result and expected result in excel file
Demo: Create 5 TCs for login function of website: http://amazon247.vn
- Test case 1 : Login without email and password (blank)
- Test case 2: Login with invalid email and password
- Test case 3: Login without email (blank) and an invalid password
- Test case 4: Login with an invalid email and without password (blank)
- Test case 5: Login with valid email and password
Step 1: Create a ‘New Package‘ file and name it as ‘Resource’, by right click on the Project and select New > Package. Place all of your test data in this folder (package) whether it is a sql file, excel file or anything.
Step 2: Place a Excel file in the above created package location and save it as TestData.xlsx. Fill the data in the excel like below image:
Step 3: Create pageObject backage and create Home_Page class
package pageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class Home_Page {
private static WebElement element = null;
public static WebElement lnk_MyAccount(WebDriver driver){
element = driver.findElement(By.id("loginBar"));
return element;
}
public static WebElement lnk_LogOut(WebDriver driver){
element = driver.findElement(By.id("account_logout"));
return element;
}
}
Step 4: Create Action package and create Login_Action class
package Action;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import pageObjects.Home_Page;
import pageObjects.Web;
import utility.ExcelForLoginCase;
public class Login_Action {
public static void Execute(int userNameRow, int userNameColumn, int passWordRow, int passWordColumn, int resultRow, int resultColumn) throws Exception {
//khai bao bien driver cua selenium
WebDriver driver = null;
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//lay gia tri url tu file excel
driver.get(ExcelForLoginCase.getCellData(0, 5));
// Get User & Password from Excel
String sUserName = ExcelForLoginCase.getCellData(userNameRow, userNameColumn);
String sPassword = ExcelForLoginCase.getCellData(passWordRow, passWordColumn);
// Send User & Password to EditText on website to login
Home_Page.lnk_MyAccount(driver).click();
WebElement btnUserName = Web.getElement(driver, "email", Web.IS_NAME); btnUserName.sendKeys(sUserName);
WebElement btnPassWord = Web .getElement(driver, "password", Web.IS_NAME); btnPassWord.sendKeys(sPassword);
btnPassWord.submit();
btnUserName = Web.getElement(driver, "email", Web.IS_NAME);
if (btnUserName == null) {
// Excel.setCellData("Pass", resultRow, resultColumn);
} else {
// Excel.setCellData("Fail", resultRow, resultColumn);
WebElement userNameMessage = Web.getElement(driver, "email-error", Web.IS_ID);
if (userNameMessage != null && userNameMessage.isDisplayed()) { System.out.println("User error");
ExcelForLoginCase.setCellData(userNameMessage.getText(), resultRow, resultColumn);
}
WebElement passWordMessage = Web.getElement(driver, "password-error", Web.IS_ID);
if (passWordMessage != null && passWordMessage.isDisplayed()) { System.out.println("Password error");
ExcelForLoginCase.setCellData(passWordMessage.getText(), resultRow, resultColumn + 1);
}
}
driver.quit(); }
}
Step 5: Create **utility **backage and create ExcelForLoginCase class
package utility;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelForLoginCase {
private final class Constant {
// Path to file excel location
public static final String Path_TestData = "src/Resource";
// Name of file excel
public static final String File_TestData = "/TestData.xlsx";
// Sheet name of file Excel
public static final String SheetName = "Login";
}
private static boolean isInit = false;
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell Cell;
private static XSSFRow Row;
private static void checkInit() throws Exception {
if (!isInit) {
setExcelFile();
} else {
return;
}
}
// This method is to set the File path and to open the Excel file, Pass
// Excel Path and Sheetname as Arguments to this method
public static void setExcelFile() throws Exception {
String Path = Constant.Path_TestData + Constant.File_TestData;
String SheetName = Constant.SheetName;
// Open the Excel file
FileInputStream ExcelFile = new FileInputStream(Path);
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
}
// This method is to read the test data from
// the Excel cell, in this we are
// passing parameters as Row num and Col num
public static String getCellData(int RowNum, int ColNum) throws Exception {
checkInit();
if (ExcelWSheet.getRow(RowNum) == null){
return "";
}
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
if (Cell == null) {
return "";
}
String CellData = Cell.toString(); //.getStringCellValue();
return CellData;
}
/**
- This method is to write in the Excel cell, Row num and Col num are the
- parameters */
public static void setCellData(String Result, int RowNum, int ColNum) throws Exception {
checkInit();
Row = ExcelWSheet.getRow(RowNum);
Cell = Row.getCell(ColNum);
if (Cell == null) {
Cell = Row.createCell(ColNum);
Cell.setCellValue(Result);
} else {
Cell.setCellValue(Result);
}
// Constant variables Test Data path and Test Data file name
FileOutputStream fileOut = new
FileOutputStream(Constant.Path_TestData
- Constant.File_TestData);
ExcelWBook.write(fileOut);
fileOut.flush();
fileOut.close();
}
}
Step 6: In automationFramework package create Apache_POI_TC class
package automationFramework;
import utility.ExcelForLoginCase;
import Action.Login_Action;
public class Apache_POI_TC {
public static void main(String[] args) throws Exception {
// Make a test with Sign In Action
int i = 2;
while (ExcelForLoginCase.getCellData(i, 0) != "") {
// SignIn_Action.Execute(i, 1, i, 2, i, 3);
Login_Action.Execute(i, 1, i, 2, i, 6);
i++;
}
}
}
Step 7: Run Apache_POI_TC.java .Once it finished open the Excel file and check for the result.
Video illustration Login funtion and show actual result and expected result in excel file
https://www.youtube.com/watch?v=fEPZpw4INFY&feature=youtu.be
4. Comparison of IDE & WebDriver
Thank you so much for your concern.
If you have any questions, please feel free to send email to le.thi.hien@framgia.com
All rights reserved