Implementing openBrowser And closeBrowser Functions In WebDriver Test

Whenever you start your any webdriver test, First of all you need to start your browser. And at the end of your test, You need to close your browser. Now supposing you have 100s of test cases then you will write browser opening and closing code In each and every test? Or supposing you wants to run all your tests In Google chrome browser Instead of Mozilla Firefox browser then you will go to change code In your each and every test cases?

Other one thing you need to verify before opening new browser In selenium webdriver Is -> Supposing you are running multiple webdriver test cases and browser Is already opened during previous test execution then you do not wants to open new browser. In this case, You will have to put special check which can verify that If browser Is already opened during previous test execution then do not open new browser and start executing test In existing browser.


To overcome all these things, You have to create common function which can perform bellow given actions.
  1. Can Open browser when you call It from any test case.
  2. Can open browser As per your choice. Means If you wants to run all your test In google chrome browser then You can do It by changing just single word.
  3. Can check If browser window Is already opened during previous test execution then do not open new window and start execution In existing window.
Follow bellow given steps for configure initBrowser() function which can perform all above things.
  • Create Testng_Pack package Under your project folder.
  • Under Testng_Pack package, Create new file(Right click on package folder-> New-> File) named SYSPARAM.properties.
  • Under Testng_Pack package, Create new class(If not exist) named CommonFunctions. If you have experimented my previous posts examples of creating general function to COMPARE TWO STRINGS, INTEGERS, DOUBLES then you will have already CommonFunctions class.
  • Under Testng_Pack package, Create new class called openCloseBrowser_Test. Now your package structure will looks like bellow.


Copy paste bellow give lines In SYSPARAM.properties file.
SYSPARAM.properties
#CHRM
BrowserToTestIn=MFF

In above SYSPARAM.properties file, If you will set BrowserToTestIn = CHRM then your all tests will be executed In Google chrome browser.


Copy paste bellow given lines In CommonFunctions class.
CommonFunctions.java
package Testng_Pack;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class CommonFunctions {
 public static WebDriver driver=null; 
 public boolean browserAlreadyOpen=false;
 public static Properties SYSPARAM =null;
 
 //To Initialize .properties file.
 public void initData() throws IOException{
  SYSPARAM = new Properties();
  FileInputStream Ist = new FileInputStream(System.getProperty("user.dir")+"//src//Testng_Pack//SYSPARAM.properties");
  SYSPARAM.load(Ist);
 }
 
 public void initBrowser(){
  //Check If browser Is already opened during previous test execution.
  if(!browserAlreadyOpen){
   //Read value of 'BrowserToTestIn' key from SYSPARAM.properties file.
   //If key value Is MMF then execute If statement
   //If key value Is CHRM then execute else statement.
   if(SYSPARAM.getProperty("BrowserToTestIn").equals("MFF")){
    System.setProperty("webdriver.gecko.driver", "D:\\Selenium Files\\geckodriver.exe");
    driver = new FirefoxDriver();   
   }else if(SYSPARAM.getProperty("BrowserToTestIn").equals("CHRM")){
    //Write lines to open chrome browser.
    driver = new ChromeDriver();
   }
  driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  //At last browserAlreadyOpen flag will becomes true to not open new browser when start executing next test.
  browserAlreadyOpen=true;
  }
 } 
  //To Close Browser
 public void closeBrowser(){
  driver.quit();
  browserAlreadyOpen=false;
 } 
}

Now I can call initBrowser() function In all my test cases to open browser. I have simple example of single test case as bellow. You can create multiple test cases and call initBrowser() function at beginning of test case and . Look at bellow given example.

openCloseBrowser_Test
package Testng_Pack;

import java.io.IOException;

import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class openCloseBrowser_Test extends CommonFunctions{

 
 @BeforeTest
 public void StartBrowser_NavURL() throws IOException {
  initData();  
 }
 
 @AfterTest
 public void ClosingBrowser() {  
  closeBrowser();  
 }
 
 @Test
 public void OpenBrowserAndURL(){
  initBrowser();
  driver.get("http://only-testing-blog.blogspot.com/");
 }
}

This way, Now I can call initBrowser() and closeBrowser(); function In any of my test case whic will reduce the size of my code and I have to change only one parameter to change browser. You can write other browsers opening syntax Inside initBrowser(); with else syntax If you wants to run your test In any other browser.

9 comments:

  1. Getting error -
    java.lang.Exception: Method StartBrowser_NavURL() should be static
    java.lang.Exception: Method ClosingBrowser() should be static

    I have replaced Testng annotations with junit annotations in same code.
    How can i get it fixed ?

    ReplyDelete
    Replies
    1. looks static and non static related Issue. Please try by making StartBrowser_NavURL() and ClosingBrowser() static method

      Delete
    2. Hi Aravind,

      Modified the error giving methods with static keyword ,and it worked.
      Thanks for immediate reply.

      Delete
  2. Hi Aravind,
    When I change SYSPARAM.properties to run with Chrome, I get NullPointerException, could you please help:

    FAILED CONFIGURATION: @AfterTest ClosingBrowser
    java.lang.NullPointerException
    at CommonFunc.OpenCloseBrowser.closeBrowser(OpenCloseBrowser.java:44)
    at CommonFunc.OpenCloseBrowserTest.ClosingBrowser(OpenCloseBrowserTest.java:19)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)


    *More info:*
    SYSPARAM.properties contains only: browserType=CHRM

    I even added System.setProperty("webdriver.chrome.driver","D:\\chromedriver_win32\\chromedriver.exe");
    to initBrowser() but it does not help

    Thanks,
    Serena


    ReplyDelete
    Replies
    1. Have you used above example as it is? or modified anything? Is it works fine for MFF?

      Delete
    2. When I run it as is, it works fine. The test is passed with FireFox.
      When I mmodified it to run with CHrome, it returns NullPointerException

      *What I had changed:
      Case1: change SYSPARAM.properties to contain only: browserType=CHRM

      Case2: change SYSPARAM.properties to contain only: BrowserToTestIn=CHRM

      Case 3:
      +change SYSPARAM.properties to contain only: browserType=CHRM
      +add this line to initBrowser() :
      System.setProperty("webdriver.chrome.driver","D:\\chromedriver_win32\\chromedriver.exe");

      But all does not work

      Delete
  3. Aravind,
    I'm able to make it work now, but still need your help to confirm if it's the real root cause:

    1. SYSPARAM.properties
    BrowserToTestIn =CHRM

    2. initBrowser(): I change else if statement a little bit:

    else if(SYSPARAM.getProperty("BrowserToTestIn").equals("CHRM")){
    //Write lines to open chrome browser.
    System.setProperty("webdriver.chrome.driver","D:\\chromedriver_win32\\chromedriver.exe");
    driver = new ChromeDriver();
    }

    You see that that I changed SYSPARAM.getProperty("browserType") to SYSPARAM.getProperty("BrowserToTestIn").
    And I added in System.setProperty("webdriver.chrome.driver","D:\\chromedriver_win32\\chromedriver.exe");

    ReplyDelete
    Replies
    1. Problem was in my example code. I have modified it and now i think it will works for you.

      Delete
    2. It works properly now.
      Thanks for your reply Aravind!

      Delete