Monday, November 23, 2020

Selenium Java POI data driven

 https://www.browserstack.com/guide/data-driven-framework-in-selenium


Let’s write a code snippet to read the data files.

Step 1: Go to the Eclipse IDE and create a project. Add all the dependencies for TestNG, Selenium and Apache POI.

Step 2: Create a class file to write the functionality.

import org.openqa.selenium.By;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class ExcelExample{
@Test(dataProvider="testdata")
public void demoClass(String username, String password) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "Path of Chrome Driver");
Webdriver driver = new ChromeDriver();
driver.get("<a href="https://www.browserstack.com/users/sign_in</a>");
driver.findElement(By.name("user[login]")).sendKeys(username);
driver.findElement(By.name("user[password]")).sendKeys(password);
driver.findElement(By.name("commit")).click();
Thread.sleep(5000);
Assert.assertTrue(driver.getTitle().matches("BrowserStack Login | Sign Into The Best Mobile & Browser Testing Tool"), "Invalid credentials");
System.out.println("Login successful");
}
@AfterMethod
void ProgramTermination() {
driver.quit();
} 
@DataProvider(name="testdata")
public Object[][] testDataExample(){
ReadExcelFile configuration = new ReadExcelFile("Path_of_Your_Excel_File");
int rows = configuration.getRowCount(0);
Object[][]signin_credentials = new Object[rows][2];

for(int i=0;i<rows;i++)
{
signin_credentials[i][0] = config.getData(0, i, 0);
signin_credentials[i][1] = config.getData(0, i, 1);
}
return signin_credentials;
}
}

In the above code, there is a “TestDataExample() method” in which the user has created an object instance of another class named “ReadExcelFile”. The user has mentioned the path to the excel file. The user has further defined a for loop to retrieve the text from the excel workbook. But to fetch the data from the excel file, one needs to write a class file for the same.

Try Running Selenium Tests on Cloud for Free

import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelFile{
XSSFWorkbook work_book;
XSSFSheet sheet;
public ReadExcelFile(String excelfilePath) {
try {
File s = new File(excelfilePath);
FileInputStream stream = new FileInputStream(s);
work_book = new XSSFWorkbook(stream);
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
public String getData(int sheetnumber, int row, int column){
sheet = work_book.getSheetAt(sheetnumber);
String data = sheet.getRow(row).getCell(column).getStringCellValue();
return data;
} 
public int getRowCount(int sheetIndex){
int row = work_book.getSheetAt(sheetIndex).getLastRowNum();
row = row + 1;
return row;
}

In the code above, the user has used Apache POI libraries to fetch the data from the excel file. Next, it will point to the data present in the excel file and then enter the relevant username and password to the sign in page.

Note: The same thing can be done using a Data provider in TestNG. But to fetch the data from the Excel sheet, the user needs Apache POI jar files.

Note: Please enter one valid credential to test.

Advantages of Data Driven Testing Framework

  1. Allows testing of the application with multiple sets of data values during regression testing
  2. Separates the test case data from the executable test script
  3. Allows reusing of Actions and Functions in different tests
  4. Generates test data automatically. This is helpful when large volumes of random test data are necessary
  5. Results in the creation of extensive code that is flexible and easy to maintain
  6. Lets developers and testers separate the logic of their test cases/scripts from the test data
  7. Allows execution of test cases several times which helps to reduce test cases and scripts
  8. It does not let changes in test scripts affect the test data.

By incorporating data-driven testing using Selenium, testers can refine their test cases for more efficient execution. This shortens timelines, makes their lives easier and results in more thoroughly tested and better quality software.

Saturday, November 21, 2020

Page Factory

 From 

https://www.browserstack.com/guide/page-object-model-in-selenium

Page Object Model and Page Factory are tools in Selenium that are popularly used in test automation. This tutorial will demonstrate how to make use of Page Object Model and Page Factory in automation projects in order to maintain test cases easily.

What is Page Object Model in Selenium?

Page Object Model, also known as POM is a design pattern in Selenium that creates an object repository for storing all web elements. It is useful in reducing code duplication and improves test case maintenance.

In Page Object Model, consider each web page of an application as a class file. Each class file will contain only corresponding web page elements. Using these elements, testers can perform operations on the website under test.

Advantages of Page Object Model

  • Helps with easy maintenance: POM is useful when there is a change in a UI element or there is a change in an action. An example would be if a drop down menu is changed to a radio button.

In this case, POM helps to identify the page or screen to be modified. As every screen will have different java files, this identification is necessary to make the required changes in the right files. This makes test cases easy to maintain and reduces errors.

  • Helps with reusing code: As already discussed, all screens are independent. By using POM, one can use the test code for any one screen, and reuse it in another test case. There is no need to rewrite code, thus saving time and effort.
  • Readability and Reliability of scripts: When all screens have independent java files, one can easily identify actions that will be performed on a particular screen by navigating through the java file. If a change must be made to a certain section of code, it can be efficiently done without affecting other files.

Implementing POM in Selenium Project

As already discussed, each java class will contain a corresponding page file. This tutorial will create 2-page files.

  • BrowserStackHomePage
  • BrowserStackSignUpPage

Each of these files will contain UI elements or Objects which are present on these screens. It will also contain the operations to be performed on these elements.


Also Read: How to Build and Execute Selenium Projects


Sample Project Structure for POM

page object model in selenium

BrowserStackHomePage Java File

POM in selenium - Java File
Explanation of Code

  • Code Line-10 to 11: Identifying elements present on BrowserStack Home Page such as header and Get Started button
  • Code Line-17 to 24: Performing actions on identified objects on BrowserStack Home Page

Code Snippet:

package browserStackPages;
import static org.testng.Assert.assertEquals;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class BrowserStackHomePage {

WebDriver driver;
By Header=By.xpath("//h1");
By getStarted=By.xpath("//*[@id='signupModalButton']");

public BrowserStackHomePage(WebDriver driver) {
this.driver=driver;
}
public void veryHeader() {
String getheadertext=driver.findElement(Header).getText();
assertEquals("App & Browser Testing Made Easy", getheadertext);
}
public void clickOnGetStarted() {
driver.findElement(getStarted).click();
}
}

BrowserStackSignUpPage Java File

pom in selenium

Explanation of Code

  • Code Line-10 to 14: Identifying elements present on BrowserStack SignUp Page such as header and Get Started button
  • Code Line-20 to 35: Performing actions on identified objects on BrowserStack SignUp Page

Code Snippet:

package browserStackPages;
import static org.testng.Assert.assertEquals;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class BrowserStackSignUpPage {
WebDriver driver;
By Header = By.xpath("//h1");
By userName = By.xpath("//*[@id='user_full_name']");
By businessEmail = By.xpath("//*[@id='user_email_login']");
By password = By.xpath("//*[@id='user_password']");
public BrowserStackSignUpPage(WebDriver driver) {
this.driver = driver;
}
public void veryHeader() {
String getheadertext = driver.findElement(Header).getText().trim();
assertEquals("Create a FREE Account", getheadertext);
}
public void enterFullName(String arg1) {
driver.findElement(userName).sendKeys(arg1);
}
public void enterBusinessEmail(String arg1) {
driver.findElement(businessEmail).sendKeys(arg1);
}
public void enterPasswrod(String arg1) {
driver.findElement(password).sendKeys(arg1);
}
}

BrowserStackSetup Java File

pom in selenium

Explanation of Code

  • Code Line-21 to 27: Setting up of browser and website to execute test scripts
  • Code Line-29 to 43: Initializing driver object to BrowserStackHomePage & BrowserStackSignUpPage and performing actions on those pages

Code Snippet:

package browserStackSetup;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import browserStackPages.BrowserStackHomePage;
import browserStackPages.BrowserStackSignUpPage;
public class BrowserStackSetup {
String driverPath = "C:\\geckodriver.exe";
WebDriver driver;
BrowserStackHomePage objBrowserStackHomePage;
BrowserStackSignUpPage objBrowserStackSignUpPage;
@BeforeTest
public void setup() {
System.setProperty("webdriver.chrome.driver", "C:\\BrowserStack\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://www.browserstack.com/");
}
@Test(priority = 1)
public void navigate_to_homepage_click_on_getstarted() {
objBrowserStackHomePage = new BrowserStackHomePage(driver);
objBrowserStackHomePage.veryHeader();
objBrowserStackHomePage.clickOnGetStarted();
}
@Test(priority = 2)
public void enter_userDetails() {
objBrowserStackSignUpPage = new BrowserStackSignUpPage(driver);
objBrowserStackSignUpPage.veryHeader();
objBrowserStackSignUpPage.enterFullName("TestUser");
objBrowserStackSignUpPage.enterBusinessEmail("TestUser@gmail.com");
objBrowserStackSignUpPage.enterPasswrod("TestUserPassword");
}
}

Run Selenium Tests for Free

What is Page Factory in Selenium?

Page Factory is a class provided by Selenium WebDriver to support Page Object Design patterns. In Page Factory, testers use @FindBy annotation. The initElements method is used to initialize web elements.

  • @FindBy: An annotation used in Page Factory to locate and declare web elements using different locators. Below is an example of declaring an element using @FindBy
@FindBy(id="elementId") WebElement element;

Similarly, one can use @FindBy with different location strategies to find the web elements and perform actions on them. Below are locators that can be used:

      • ClassName
      • Css
      • Name
      • Xpath
      • TagName
      • LinkText
      • PartialLinkText
  • initElements()initElements is a static method in Page Factory class. Using the initElements method, one can initialize all the web elements located by @FindBy annotation.
  • lazy initialization: AjaxElementLocatorFactory is a lazy load concept in Page Factory. This is used to identify web elements only when they are used in any operation or activity. The timeout of a web element can be assigned to the object class with the help of the AjaxElementLocatorFactory.

Implementing Page Factory in Selenium Project

This will try to use the same project used for the POM Model. It will reuse the 2-page files and implement Page Factory.

  • BrowserStackHomePage
  • BrowserStackSignUpPage

As discussed earlier, each of these files will only contain UI elements or Objects which are present on these screens along with the operations to be performed on these elements.

Sample Project Structure for Page Factory

The project structure will not be changing as the same project is being used. As already mentioned, Page Factory supports Page Object Model design pattern.

page factory in selenium

BrowserStackHomePage Java File

page factory in selenium - java file
Explanation of Code

Code Line-13 to 17: Identifying elements present on BrowserStack Home Page such as header and Get Started button using Page Factory @FindBy annotation

Code Line-23 to 30: Performing actions on identified objects on BrowserStack Home Page

Code Snippet:

package browserStackPages;
import static org.testng.Assert.assertEquals;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class BrowserStackHomePage {
WebDriver driver;
@FindBy(xpath = "//h1")
WebElement Header;
@FindBy(xpath = "//*[@id='signupModalButton']")
WebElement getStarted;
public BrowserStackHomePage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void veryHeader() {
String getheadertext = Header.getText();
assertEquals("App & Browser Testing Made Easy", getheadertext);
}
public void clickOnGetStarted() {
getStarted.click();
}
}

BrowserStackSignUpPage Java File

page factory in selenium

Explanation of Code

Code Line-14 to 24: Identifying elements present on BrowserStack SignUp Page such as header and Get Started button using Page Factory @FindBy annotation.
Code Line-26 to 46: Performing actions on identified objects on BrowserStack SignUp Page

Code Snippet:

package browserStackPages;
import static org.testng.Assert.assertEquals;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class BrowserStackSignUpPage {
WebDriver driver;
@FindBy(xpath = "//h1")
WebElement Header;
@FindBy(xpath = "//*[@id='user_full_name']")
WebElement userName;
@FindBy(xpath = "//*[@id='user_email_login']")
WebElement businessEmail;
@FindBy(xpath = "//*[@id='user_password']")
WebElement password;
public BrowserStackSignUpPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void veryHeader() {
String getheadertext = Header.getText().trim();
assertEquals("Create a FREE Account", getheadertext);
}
public void enterFullName(String arg1) {
userName.sendKeys(arg1);
}
public void enterBusinessEmail(String arg1) {
businessEmail.sendKeys(arg1);
}
public void enterPasswrod(String arg1) {
password.sendKeys(arg1);
}
}

BrowserStackSetup Java File

page factory in selenium - sample project
Explanation of Code

  • Code Line-21 to 27: Setting up of browser and website to execute our scripts
  • Code Line-29 to 43: Initializing driver objects to BrowserStackHomePage & BrowserStackSignUpPage and performing actions on those pages

Code Snippet:

package browserStackSetup;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import browserStackPages.BrowserStackHomePage;
import browserStackPages.BrowserStackSignUpPage;
public class BrowserStackSetup {
String driverPath = "C:\\geckodriver.exe";
WebDriver driver;
BrowserStackHomePage objBrowserStackHomePage;
BrowserStackSignUpPage objBrowserStackSignUpPage;
@BeforeTest
public void setup() {
System.setProperty("webdriver.chrome.driver", "C:\\BrowserStack\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://www.browserstack.com/");
}
@Test(priority = 1)
public void navigate_to_homepage_click_on_getstarted() {
objBrowserStackHomePage = new BrowserStackHomePage(driver);
objBrowserStackHomePage.veryHeader();
objBrowserStackHomePage.clickOnGetStarted();
}
@Test(priority = 2)
public void enter_userDetails() {
objBrowserStackSignUpPage = new BrowserStackSignUpPage(driver);
objBrowserStackSignUpPage.veryHeader();
objBrowserStackSignUpPage.enterFullName("TestUser");
objBrowserStackSignUpPage.enterBusinessEmail("TestUser@gmail.com");
objBrowserStackSignUpPage.enterPasswrod("TestUserPassword");
}
}

Test Result:

page object model with pagefactory in selenium

Try Selenium Testing on Real Devices for Free

Difference Between Page Object Model and Page Factory in Selenium

Page Object ModelPage Factory
Finding web elements using ByFinding web elements using @FindBy
POM does not provide lazy initializationPage Factory does provide lazy initialization
Page Object Model is a design patternPageFactory is a class which provides implementation of Page Object Model design pattern
In POM, one needs to initialize every page object individuallyIn PageFactory, all page objects are initialized by using the initElements() method

Run the code in order to test the workings of Page Object Model and Page Factory. Since these are important Selenium functions, testers need to be able to use them with ease and accuracy for Selenium automation. This will help them streamline automation testing efforts and yield results quicker.

API interview questions

  https://www.katalon.com/resources-center/blog/web-api-testing-interview-questions/ Top 50+ Web API Testing Interview Questions [Ultimate l...