Friday, 26 January 2018

6. Base Class for the framework

Introducing the Base Class


This chapter will focus on the heart of our framework ie. The base class. This base class will serve as a parent class for the page objects and the test classes. One advantage of using the base class is you can have all the common functionality like clicking of buttons(including radio buttons and checkboxes), selecting items from dropdown lists, wait functionality, Javascript executor functionality.

All the code in the book will be built along the way and detailed explanation of each code snippet will be given. Let's start with the skeleton of the base class. The base class will create a singleton WebDriver instance. This class will have a private constructor and a public method preferably name getInstance() that returns the same instance of WebDriver each time.

package hrdemoapp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;

public class BaseClass {
static WebDriver driver=null;
   public BaseClass(){
   driver = SingletonDriver.getSigletonInstance();
   }
   public static void initApp(){
   String URL=getProperty("URL");
   navigateToURL(URL);
   }
   public static void navigateToURL(String URL){
        driver.manage().timeouts().implicitlyWait(160, TimeUnit.SECONDS);
    driver.navigate().to(URL);
    }

   static File file = new File(".//src/main/resources/config/config.properties");
   public static String getProperty(String propKey){  
FileInputStream fileInput = null;
try {
fileInput = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Properties prop = new Properties();
//load properties file
try {
prop.load(fileInput);
} catch (IOException e) {
e.printStackTrace();
}
return prop.getProperty(propKey);
   }
   
   public static void enterText(WebElement elem,String text){
   elem.sendKeys(text);
   }
   
   public static void clickButton(WebElement elem){
   elem.click();
   }
   public static void clickLink(WebElement elem){
   elem.click();
   }
   public static void selectValue(WebElement elem,String selText){
   new Select(elem).selectByVisibleText(selText);
   }

}

The line highlighted above is a call to the static method getSingletonInstance() in the SingletonDriver class. Static methods dont need the object of a class. Rather we invoke the static methods in class using the class name 

No comments:

Post a Comment