Automation Using Selenium Webdriver

Wednesday, 28 September 2016

Java Object Oriented

Inheritance in Java

The process of obtaining the data members and methods from one class to another class is known as inheritance. It is one of the fundamental features of object-oriented programming.

Important points

  • In the inheritance the class which is give data members and methods is known as base or super or parent class.
  • The class which is taking the data members and methods is known as sub or derived or child class.
  • The data members and methods of a class are known as features.
  • The concept of inheritance is also known as re-usability or extendable classes or sub classing or derivation.

Why use Inheritance ?

  • For Method Overriding (used for Runtime Polymorphism).
  • It's main uses are to enable polymorphism and to be able to reuse code for different classes by putting it in a common super class
  • For code Re-usability
  • Syntax of Inheritance

    class Subclass-Name extends Superclass-Name  
    {  
       //methods and fields  
    }  
  • Real life example of inheritance

    The real life example of inheritance is child and parents, all the properties of father are inherited by his son.
  • Real life example of inheritance

    The real life example of inheritance is child and parents, all the properties of father are inherited by his son.
    real life example of inheritance
  • The following diagram use view about inheritance
  • In the above diagram data members and methods are represented in broken line are inherited from faculty class and they are visible in student class logically.

    Advantage of inheritance

    If we develop any application using concept of Inheritance than that application have following advantages,
    • Application development time is less.
    • Application take less memory.
    • Application execution time is less.
    • Application performance is enhance (improved).
    • Redundancy (repetition) of the code is reduced or minimized so that we get consistence results and less storage cost.
    Note: In Inheritance the scope of access modifier increasing is allow but decreasing is not allow. Suppose in parent class method access modifier is default then it's present in child class with default or public or protected access modifier but not private(it decreased scope).

    Tpyes of Inheritance

    Based on number of ways inheriting the feature of base class into derived class we have five types of inheritance; they are:
    • Single inheritance
    • Multiple inheritance
    • Hierarchical inheritance
    • Multilevel inheritance
    • Hybrid inheritance

    Single inheritance

    In single inheritance there exists single base class and single derived class.

    Example of Single Inheritance

    class Faculty
    {  
    float salary=30000;  
    }  
    class Science extends Faculty
    { 
    float bonous=2000;
    public static void main(String args[])
    {
    Science obj=new Science(); 
    System.out.println("Salary is:"+obj.salary);  
    System.out.println("Bonous is:"+obj.bonous);  
    }  
    } 

    Output

    Salary is: 30000.0
    Bonous is: 2000.0
    
    single inheritance

    Multilevel inheritances in Java

    In Multilevel inheritances there exists single base class, single derived class and multiple intermediate base classes.
    Single base class + single derived class + multiple intermediate base classes.

    Intermediate base classes

    An intermediate base class is one in one context with access derived class and in another context same class access base class.
  • Hence all the above three inheritance types are supported by both classes and interfaces.

    Example of Multilevel Inheritance

    class Faculty
    {  
    float total_sal=0, salary=30000;  
    }  
    
    class HRA extends Faculty
    {  
    float hra=3000;  
    }  
    
    class DA extends HRA
    {  
    float da=2000;  
    }  
    
    class Science extends DA
    { 
    float bonous=2000;
    public static void main(String args[])
    {
    Science obj=new Science(); 
    obj.total_sal=obj.salary+obj.hra+obj.da+obj.bonous;
    System.out.println("Total Salary is:"+obj.total_sal);   
    }  
    }

    Output

    Total Salary is: 37000.0
    

    Multiple inheritance

    In multiple inheritance there exist multiple classes and singel derived class.
    multiple inheritance
    The concept of multiple inheritance is not supported in java through concept of classes but it can be supported through the concept of interface.

    Hybrid inheritance

    Combination of any inheritance type
    In the combination if one of the combination is multiple inheritance then the inherited combination is not supported by java through the classes concept but it can be supported through the concept of interface.
    hybrid inheritance

    Inheriting the feature from base class to derived class

    In order to inherit the feature of base class into derived class we use the following syntax

    Syntax

    class ClassName-2 extends ClasssName-1
    {
    variable  declaration;
    Method declaration;
    }
    extends keyword

    Explanation

    1. ClassName-1 and ClassName-2 represents name of the base and derived classes respectively.
    2. extends is one of the keyword used for inheriting the features of base class into derived class it improves the functionality of derived class.

    Important Points for Inheritance:

    • In java programming one derived class can extends only one base class because java programming does not support multiple inheritance through the concept of classes, but it can be supported through the concept of Interface.
    • Whenever we develop any inheritance application first create an object of bottom most derived class but not for top most base class.
    • When we create an object of bottom most derived class, first we get the memory space for the data members of top most base class, and then we get the memory space for data member of other bottom most derived class.
    • Bottom most derived class contains logical appearance for the data members of all top most base classes.
    • If we do not want to give the features of base class to the derived class then the definition of the base class must be preceded by final hence final base classes are not reusable or not inheritable.
    • If we are do not want to give some of the features of base class to derived class than such features of base class must be as private hence private features of base class are not inheritable or accessible in derived class.
    • Data members and methods of a base class can be inherited into the derived class but constructors of base class can not be inherited because every constructor of a class is made for initializing its own data members but not made for initializing the data members of other classes.
    • An object of base class can contain details about features of same class but an object of base class never contains the details about special features of its derived class (this concept is known as scope of base class object).
    • For each and every class in java there exists an implicit predefined super class called java.lang.Object. because it providers garbage collection facilities to its sub classes for collecting un-used memory space and improved the performance of java application.

    Example of Inheritance

    class Faculty
    {  
    float salary=30000;  
    }  
    class Science extends Faculty
    { 
    float bonous=2000;
    public static void main(String args[])
    {
    Science obj=new Science(); 
    System.out.println("Salary is:"+obj.salary);  
    System.out.println("Bonous is:"+obj.bonous);  
    }  
    } 

    Output

    Salary is: 30000.0
    Bonous is: 2000.0
    

    Why multiple inheritance is not supported in java?

    Due to ambiguity problem java does not support multiple inheritance at class level.

    Example

    class A
    {
    void disp()
    {
    System.out.println("Hello");
    }
    }
    class B
    {
    void disp()
    System.out.println("How are you ?");
    }
    }
    class C extends A,B  //suppose if it were
    {
    Public Static void main(String args[])
    {  
    C obj=new C();  
    obj.disp();//Now which disp() method would be invoked?  
    }  
    }  
    In above code we call both class A and class B disp() method then it confusion which class method is call. So due to this ambiguity problem in java do not use multiple inheritance at class level, but it support at interface level.

    Difference between Java Inheritance and C++ Inheritance

    The main difference between java Inheritance and C++ Inheritance is; Java doesn’t support multiple inheritance but C++ support.



On test case failure take a screenshot with Selenium WebDriver

Take Screen Shot in Selenium

We have discussed about simple way of taking a screen shot earlier. Now in this , 
we will see how to take screen shot.


import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;


public class Screenshoot {

public static WebDriver driver;
public static void main(String[] args) throws IOException
{
//Step1:Launch FirefoxDriver
        //Step2:Navigate to http://newtours.demoaut.com/
//Take screenshot
System.out.println("********Excution stating wait*********");
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
driver=new ChromeDriver();
driver.get("http://newtours.demoaut.com/");
//code for taking screenshot
File Srcfile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(Srcfile, new File("E:\\Jagan\\Screenshot.png"));
System.out.println("Screen shot taken");
        driver.close();
}


}Take Screen Shot in selenium


On test case failure take a screenshot with Selenium WebDriverOn test case failure take a screenshot with Selenium WebDriver


Don't you think "A picture is worth a thousand words.." :)

It is always(at least in most of the cases :P) better to take screenshot of webpage when
the test runfails.

Because with one look at the screenshot we can get an idea of where exactly the script got failed.
Moreover reading screenshot is easier compare to reading 100's of console errors :P

Here is the sample code to take screenshot of webpage
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

FileUtils.copyFile(scrFile, new File("PathOnLocalDrive")

To get screenshot on test failure , we should put the entire code in try-catch block . In the catch block
make sure to copy the above screenshot code.

In my example I am trying to register as a new user. For both first and last name fields
I have used correct locator element whereas for emailaddress field I have used wrong locator
element i.e name("GmailAddress1").

So when I run the script , test failed and I got the screenshot with pre filled first and last names
but not email address.

Here is the sample code :
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class TakeScreenshot {
 
   WebDriver driver;
 
 @BeforeTest
 public void start(){
  driver = new FirefoxDriver();
 }
 
 @Test
 public void Test() throws IOException{
 try{
  driver.get("https://mail.google.com/");
  driver.findElement(By.id("link-signup")).click();
  driver.findElement(By.name("FirstName")).sendKeys("First Name");
  driver.findElement(By.name("LastName")).sendKeys("Last Name");
  driver.findElement(By.name("GmailAddress1")).sendKeys("GmailAddress@gmail.com");
  
 }catch(Exception e){
  //Takes the screenshot  when test fails
     File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
     FileUtils.copyFile(scrFile, new File("E:\\jagan\\failure.png"));
   
  }
 }
}
And here is the screenshot of webpage on test failure

On test case failure take a screenshot with Selenium WebDriver

Monday, 26 September 2016

Simple Page Object Model Example(POM)

Simple Page Object Model Frame work example

What is POM (Page Object Model) and what is the need of it?

Ans- Page Object Model Framework has now a days become very popular test automation framework in the industry and many companies are using it because of its easy test maintenance and reduces the duplication of code.The main advantage of Page Object Model is that if the UI changes for any page, it doesn’t require us to change any tests, we just need to change only the code within the page objects (Only at one place). Many other tools which are using selenium, are following the page object model.
The Page Object model provides the following advantages.
1. There is clean separation between test code and page specific code such as locators (or their use if you’re using a UI map) and layout.2. There is single repository for the services or operations offered by the page rather than having these services scattered throughout the tests.
************************------------------******************

 

Step 1: Create the Test Setup class
This the main class for page object model, where we will create Webdriver object based on the browser type passed as aparameter in textng.xml file. We will also need to pass the base page application URL in testng.xml as parameter.
In this example we have taken only two browsers the default Firefox and chrome browser. To initiate Chrome browser, we need to set the System Property by providing the chromedriver exe path.
We need to create a method to return Webdriver 'driver' where this is used for test execution.
Below is the example TestBaseSetup.class file
package com.pack.base;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;

public class TestBaseSetup {

 private WebDriver driver;
 static String driverPath = "D:\\chromedriver\";

 public WebDriver getDriver() {
  return driver;
 }

 private void setDriver(String browserType, String appURL) {
  switch (browserType) {
  case "chrome":
   driver = initChromeDriver(appURL);
   break;
  case "firefox":
   driver = initFirefoxDriver(appURL);
   break;
  default:
   System.out.println("browser : " + browserType
     + " is invalid, Launching Firefox as browser of choice..");
   driver = initFirefoxDriver(appURL);
  }
 }

 private static WebDriver initChromeDriver(String appURL) {
  System.out.println("Launching google chrome with new profile..");
  System.setProperty("webdriver.chrome.driver", driverPath
    + "chromedriver.exe");
  WebDriver driver = new ChromeDriver();
  driver.manage().window().maximize();
  driver.navigate().to(appURL);
  return driver;
 }

 private static WebDriver initFirefoxDriver(String appURL) {
  System.out.println("Launching Firefox browser..");
  WebDriver driver = new FirefoxDriver();
  driver.manage().window().maximize();
  driver.navigate().to(appURL);
  return driver;
 }

 @Parameters({ "browserType", "appURL" })
 @BeforeClass
 public void initializeTestBaseSetup(String browserType, String appURL) {
  try {
   setDriver(browserType, appURL);

  } catch (Exception e) {
   System.out.println("Error....." + e.getStackTrace());
  }
 }
 
 @AfterClass
 public void tearDown() {
  driver.quit();
 }
}Step 2: Now We will create Page Object classes. For each page we will create a separate class with constructor. We identify the locators and keep all together on just below the class. This will help us to re-use the locators for multiple methods and the main important is, we can easily find the locator and change if required.
We need to identify and list of all the possible functionalities on this page and we should write methods in such a way they are re-used. When ever there is a method to click on a button or link, we should return driver object of that page.
We will look into the below example. For method SignInBtn, we are returning after clicking on Sign In button as it is redirecting to sign in page.
BasePage.class
In the below SignInpage.class, we have methods to click on create account and sign in button. We are just verifying an error in sign in page for now in this example.
SignInPage.class
package come.pack.common.pageobjects;

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

public class SignInPage {

private WebDriver driver;

private By headerPageText = By.cssSelector(".hidden-small");
private By createAccountLink = By.id("link-signup");
private By emailTextBox = By.id("Email");
private By passwordTextBox = By.id("Passwd");
private By loginBtn = By.id("signIn");
private By errorMsgTxt = By.id("errormsg_0_Passwd");
 
 public SignInPage(WebDriver driver) {
  this.driver=driver;
 }
 
 public String getSignInPageTitle() {
  String pageTitle = driver.getTitle();
  return pageTitle;
 }
 
 public boolean verifySignInPageTitle() {
  String expectedTitle = "Sign in - Google Accounts";
  return getSignInPageTitle().contains(expectedTitle);
 }
 
 public boolean verifySignInPageText() {
  WebElement element = driver.findElement(headerPageText);
  String pageText = element.getText();
  String expectedPageText = "Sign in with your Google Account";
  return pageText.contains(expectedPageText);
 }
  public CreateAccountPage clickonCreateAnAccount() {
   WebElement element=driver.findElement(createAccountLink);
   if(element.isDisplayed()||element.isEnabled())
    element.click();
   return new CreateAccountPage(driver);
 }
  
  public boolean verifySignIn() {
   enterUserName("test");
   enterPassword("pass");
   clickOnSignIn();
   return getErrorMessage().contains("incorrect");
  }
  
  public void enterUserName(String userName) {
   WebElement emailTxtBox = driver.findElement(emailTextBox);
   if(emailTxtBox.isDisplayed())
    emailTxtBox.sendKeys(userName);
  }
  
  public void enterPassword(String password) {
   WebElement passwordTxtBox = driver.findElement(passwordTextBox);
   if(passwordTxtBox.isDisplayed())
    passwordTxtBox.sendKeys(password);
  }
  
  public void clickOnSignIn() {
   WebElement signInBtn = driver.findElement(loginBtn);
   if(signInBtn.isDisplayed())
    signInBtn.click();
  }
  
  public String getErrorMessage() {
   String strErrorMsg = null;
   WebElement errorMsg = driver.findElement(errorMsgTxt);
   if(errorMsg.isDisplayed()&&errorMsg.isEnabled())
    strErrorMsg = errorMsg.getText();
   return strErrorMsg;
  }
}CreateAccountPage.class
package come.pack.common.pageobjects;

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

public class CreateAccountPage {

 private WebDriver driver;
 private By headerPageTxt = By.cssSelector(".signuponepage.main.content.clearfix>h1");
 public CreateAccountPage(WebDriver driver) {
  this.driver=driver;
 }
 
 public String getPageTitle() {
  String title = driver.getTitle();
  return title;
 }
 
 public boolean verifyPageTitle() {
  String pageTitle = "Create your Google Account";
  return getPageTitle().contains(pageTitle);
 }
 public boolean verifyCreateAccountPageText() {
  WebElement element = driver.findElement(headerPageTxt);
  String pageText ="Create your Google Account";
  return element.getText().contains(pageText);
 }
 
 public void createAccount() {
  //need to write steps for creating an account
 }
}
Step 3: Now we will see how to write Tests for the above pages. For all the page Objects, we will now create Tests for each page. Which will help us in easy maintainability. if there is any change in the UI, we can simply change in one Page one place. We will see first example test for "BasePageTest.class".
In the below example we verifying home page by taking the title. We have written a method in BasePage and we are just calling it here.
'package com.pack.common.tests;

import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import com.pack.base.TestBaseSetup;
import come.pack.common.pageobjects.BasePage;

public class BasePageTest extends TestBaseSetup{
 
 private WebDriver driver;
 
 @BeforeClass
 public void setUp() {
  driver=getDriver();
 }
 
 @Test
 public void verifyHomePage() {
  System.out.println("Home page test...");
  BasePage basePage = new BasePage(driver);
  Assert.assertTrue(basePage.verifyBasePageTitle(), "Home page title doesn't match");
 }

}
We will look into the next test 'SignInPageTest'. In the below test, we are verifying page title, page text, and Sign in functionality. For all these verifications we have defined methods in SignInPage class which we are calling from tests.
package com.pack.common.tests;

import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import com.pack.base.TestBaseSetup;

import come.pack.common.pageobjects.BasePage;
import come.pack.common.pageobjects.SignInPage;

public class SignInPageTest extends TestBaseSetup{
private WebDriver driver;
private SignInPage signInPage;
private BasePage basePage;
 
 @BeforeClass
 public void setUp() {
  driver=getDriver();
 }
  
 @Test
 public void verifySignInFunction() {
  System.out.println("Sign In functionality details...");
  basePage = new BasePage(driver);
  signInPage = basePage.clickSignInBtn();
  Assert.assertTrue(signInPage.verifySignInPageTitle(), "Sign In page title doesn't match");
  Assert.assertTrue(signInPage.verifySignInPageText(), "Page text not matching");
  Assert.assertTrue(signInPage.verifySignIn(), "Unable to sign in");

 }

}
Now the create test 'CreateAnAccountTest'. Now we should be able to understand the verification that we are doing in the below test.
package com.pack.common.tests;

import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import com.pack.base.TestBaseSetup;

import come.pack.common.pageobjects.BasePage;
import come.pack.common.pageobjects.CreateAccountPage;
import come.pack.common.pageobjects.SignInPage;

public class CreateAnAccounTest extends TestBaseSetup {
 private WebDriver driver;
 private SignInPage signInPage;
 private BasePage basePage;
 private CreateAccountPage createAccountPage;
  
  @BeforeClass
  public void setUp() {
   driver=getDriver();
  }
  
  @Test
  public void verifyCreateAnAccounPage() {
   System.out.println("Create An Account page test...");
   basePage = new BasePage(driver);
   signInPage = basePage.clickSignInBtn();
   createAccountPage = signInPage.clickonCreateAnAccount();
   Assert.assertTrue(createAccountPage.verifyPageTitle(), "Page title not matching");
   Assert.assertTrue(createAccountPage.verifyCreateAccountPageText(), "Page text not matching");
  }
  
  public void verifySignInFunction() {
   
  }

}
Step 4: We are done with Base Setup, Page Objects creation, Tests creation. Now we will execute them using 'testng.xml' file. We will add the classes which we want to test.
Remember we need to pass the parameters 'browserType' and 'appURL' for the base Setup class.
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Page Object test example">
<parameter name="appURL" value="https://www.google.co.in/"/>
<parameter name="browserType" value="firefox"/>
  <test name="sample test">
    <classes>
      <class name="com.pack.common.tests.HomePageTest"/>
      <class name="com.pack.common.tests.SignInPageTest"/>
      <class name="com.pack.common.tests.CreateAnAccounTest"/>
    </classes>
  </test>
</suite>
The above Page Object Model framework is the simple one without using any Build tools, Loggers, Listeners and Utilities. In the next coming post we will add all these things and design a Robust Page Object Model Framework which are used in the Industry.
The below are the list of things which are commonly used in the Real time Page Object Model Framework.
1. Selenium Webdriver with Java
2. Maven Build Tool
3. TestNG (We will user TestNG Listeners also)
4. Log4j
5. Eclipse IDE
Simple Page Object Model Example(POM)

Simple Page Object Model Example(POM)

Simple Page Object Model Frame work example

What is POM (Page Object Model) and what is the need of it?

Ans- Page Object Model Framework has now a days become very popular test automation framework in the industry and many companies are using it because of its easy test maintenance and reduces the duplication of code.The main advantage of Page Object Model is that if the UI changes for any page, it doesn’t require us to change any tests, we just need to change only the code within the page objects (Only at one place). Many other tools which are using selenium, are following the page object model.
The Page Object model provides the following advantages.
1. There is clean separation between test code and page specific code such as locators (or their use if you’re using a UI map) and layout.2. There is single repository for the services or operations offered by the page rather than having these services scattered throughout the tests.
************************------------------******************

 

Step 1: Create the Test Setup class
This the main class for page object model, where we will create Webdriver object based on the browser type passed as aparameter in textng.xml file. We will also need to pass the base page application URL in testng.xml as parameter.
In this example we have taken only two browsers the default Firefox and chrome browser. To initiate Chrome browser, we need to set the System Property by providing the chromedriver exe path.
We need to create a method to return Webdriver 'driver' where this is used for test execution.
Below is the example TestBaseSetup.class file
package com.pack.base;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;

public class TestBaseSetup {

 private WebDriver driver;
 static String driverPath = "D:\\chromedriver\";

 public WebDriver getDriver() {
  return driver;
 }

 private void setDriver(String browserType, String appURL) {
  switch (browserType) {
  case "chrome":
   driver = initChromeDriver(appURL);
   break;
  case "firefox":
   driver = initFirefoxDriver(appURL);
   break;
  default:
   System.out.println("browser : " + browserType
     + " is invalid, Launching Firefox as browser of choice..");
   driver = initFirefoxDriver(appURL);
  }
 }

 private static WebDriver initChromeDriver(String appURL) {
  System.out.println("Launching google chrome with new profile..");
  System.setProperty("webdriver.chrome.driver", driverPath
    + "chromedriver.exe");
  WebDriver driver = new ChromeDriver();
  driver.manage().window().maximize();
  driver.navigate().to(appURL);
  return driver;
 }

 private static WebDriver initFirefoxDriver(String appURL) {
  System.out.println("Launching Firefox browser..");
  WebDriver driver = new FirefoxDriver();
  driver.manage().window().maximize();
  driver.navigate().to(appURL);
  return driver;
 }

 @Parameters({ "browserType", "appURL" })
 @BeforeClass
 public void initializeTestBaseSetup(String browserType, String appURL) {
  try {
   setDriver(browserType, appURL);

  } catch (Exception e) {
   System.out.println("Error....." + e.getStackTrace());
  }
 }
 
 @AfterClass
 public void tearDown() {
  driver.quit();
 }
}Step 2: Now We will create Page Object classes. For each page we will create a separate class with constructor. We identify the locators and keep all together on just below the class. This will help us to re-use the locators for multiple methods and the main important is, we can easily find the locator and change if required.
We need to identify and list of all the possible functionalities on this page and we should write methods in such a way they are re-used. When ever there is a method to click on a button or link, we should return driver object of that page.
We will look into the below example. For method SignInBtn, we are returning after clicking on Sign In button as it is redirecting to sign in page.
BasePage.class
In the below SignInpage.class, we have methods to click on create account and sign in button. We are just verifying an error in sign in page for now in this example.
SignInPage.class
package come.pack.common.pageobjects;

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

public class SignInPage {

private WebDriver driver;

private By headerPageText = By.cssSelector(".hidden-small");
private By createAccountLink = By.id("link-signup");
private By emailTextBox = By.id("Email");
private By passwordTextBox = By.id("Passwd");
private By loginBtn = By.id("signIn");
private By errorMsgTxt = By.id("errormsg_0_Passwd");
 
 public SignInPage(WebDriver driver) {
  this.driver=driver;
 }
 
 public String getSignInPageTitle() {
  String pageTitle = driver.getTitle();
  return pageTitle;
 }
 
 public boolean verifySignInPageTitle() {
  String expectedTitle = "Sign in - Google Accounts";
  return getSignInPageTitle().contains(expectedTitle);
 }
 
 public boolean verifySignInPageText() {
  WebElement element = driver.findElement(headerPageText);
  String pageText = element.getText();
  String expectedPageText = "Sign in with your Google Account";
  return pageText.contains(expectedPageText);
 }
  public CreateAccountPage clickonCreateAnAccount() {
   WebElement element=driver.findElement(createAccountLink);
   if(element.isDisplayed()||element.isEnabled())
    element.click();
   return new CreateAccountPage(driver);
 }
  
  public boolean verifySignIn() {
   enterUserName("test");
   enterPassword("pass");
   clickOnSignIn();
   return getErrorMessage().contains("incorrect");
  }
  
  public void enterUserName(String userName) {
   WebElement emailTxtBox = driver.findElement(emailTextBox);
   if(emailTxtBox.isDisplayed())
    emailTxtBox.sendKeys(userName);
  }
  
  public void enterPassword(String password) {
   WebElement passwordTxtBox = driver.findElement(passwordTextBox);
   if(passwordTxtBox.isDisplayed())
    passwordTxtBox.sendKeys(password);
  }
  
  public void clickOnSignIn() {
   WebElement signInBtn = driver.findElement(loginBtn);
   if(signInBtn.isDisplayed())
    signInBtn.click();
  }
  
  public String getErrorMessage() {
   String strErrorMsg = null;
   WebElement errorMsg = driver.findElement(errorMsgTxt);
   if(errorMsg.isDisplayed()&&errorMsg.isEnabled())
    strErrorMsg = errorMsg.getText();
   return strErrorMsg;
  }
}CreateAccountPage.class
package come.pack.common.pageobjects;

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

public class CreateAccountPage {

 private WebDriver driver;
 private By headerPageTxt = By.cssSelector(".signuponepage.main.content.clearfix>h1");
 public CreateAccountPage(WebDriver driver) {
  this.driver=driver;
 }
 
 public String getPageTitle() {
  String title = driver.getTitle();
  return title;
 }
 
 public boolean verifyPageTitle() {
  String pageTitle = "Create your Google Account";
  return getPageTitle().contains(pageTitle);
 }
 public boolean verifyCreateAccountPageText() {
  WebElement element = driver.findElement(headerPageTxt);
  String pageText ="Create your Google Account";
  return element.getText().contains(pageText);
 }
 
 public void createAccount() {
  //need to write steps for creating an account
 }
}
Step 3: Now we will see how to write Tests for the above pages. For all the page Objects, we will now create Tests for each page. Which will help us in easy maintainability. if there is any change in the UI, we can simply change in one Page one place. We will see first example test for "BasePageTest.class".
In the below example we verifying home page by taking the title. We have written a method in BasePage and we are just calling it here.
'package com.pack.common.tests;

import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import com.pack.base.TestBaseSetup;
import come.pack.common.pageobjects.BasePage;

public class BasePageTest extends TestBaseSetup{
 
 private WebDriver driver;
 
 @BeforeClass
 public void setUp() {
  driver=getDriver();
 }
 
 @Test
 public void verifyHomePage() {
  System.out.println("Home page test...");
  BasePage basePage = new BasePage(driver);
  Assert.assertTrue(basePage.verifyBasePageTitle(), "Home page title doesn't match");
 }

}
We will look into the next test 'SignInPageTest'. In the below test, we are verifying page title, page text, and Sign in functionality. For all these verifications we have defined methods in SignInPage class which we are calling from tests.
package com.pack.common.tests;

import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import com.pack.base.TestBaseSetup;

import come.pack.common.pageobjects.BasePage;
import come.pack.common.pageobjects.SignInPage;

public class SignInPageTest extends TestBaseSetup{
private WebDriver driver;
private SignInPage signInPage;
private BasePage basePage;
 
 @BeforeClass
 public void setUp() {
  driver=getDriver();
 }
  
 @Test
 public void verifySignInFunction() {
  System.out.println("Sign In functionality details...");
  basePage = new BasePage(driver);
  signInPage = basePage.clickSignInBtn();
  Assert.assertTrue(signInPage.verifySignInPageTitle(), "Sign In page title doesn't match");
  Assert.assertTrue(signInPage.verifySignInPageText(), "Page text not matching");
  Assert.assertTrue(signInPage.verifySignIn(), "Unable to sign in");

 }

}
Now the create test 'CreateAnAccountTest'. Now we should be able to understand the verification that we are doing in the below test.
package com.pack.common.tests;

import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import com.pack.base.TestBaseSetup;

import come.pack.common.pageobjects.BasePage;
import come.pack.common.pageobjects.CreateAccountPage;
import come.pack.common.pageobjects.SignInPage;

public class CreateAnAccounTest extends TestBaseSetup {
 private WebDriver driver;
 private SignInPage signInPage;
 private BasePage basePage;
 private CreateAccountPage createAccountPage;
  
  @BeforeClass
  public void setUp() {
   driver=getDriver();
  }
  
  @Test
  public void verifyCreateAnAccounPage() {
   System.out.println("Create An Account page test...");
   basePage = new BasePage(driver);
   signInPage = basePage.clickSignInBtn();
   createAccountPage = signInPage.clickonCreateAnAccount();
   Assert.assertTrue(createAccountPage.verifyPageTitle(), "Page title not matching");
   Assert.assertTrue(createAccountPage.verifyCreateAccountPageText(), "Page text not matching");
  }
  
  public void verifySignInFunction() {
   
  }

}
Step 4: We are done with Base Setup, Page Objects creation, Tests creation. Now we will execute them using 'testng.xml' file. We will add the classes which we want to test.
Remember we need to pass the parameters 'browserType' and 'appURL' for the base Setup class.
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Page Object test example">
<parameter name="appURL" value="https://www.google.co.in/"/>
<parameter name="browserType" value="firefox"/>
  <test name="sample test">
    <classes>
      <class name="com.pack.common.tests.HomePageTest"/>
      <class name="com.pack.common.tests.SignInPageTest"/>
      <class name="com.pack.common.tests.CreateAnAccounTest"/>
    </classes>
  </test>
</suite>
The above Page Object Model framework is the simple one without using any Build tools, Loggers, Listeners and Utilities. In the next coming post we will add all these things and design a Robust Page Object Model Framework which are used in the Industry.
The below are the list of things which are commonly used in the Real time Page Object Model Framework.
1. Selenium Webdriver with Java
2. Maven Build Tool
3. TestNG (We will user TestNG Listeners also)
4. Log4j
5. Eclipse IDE