1
votes

I have two classes each having some tests.I am providing the class names in the testng xml. When I execute the XML, only the class-1 executes and in the result, there will be a Null Pointer exception. I am trying to develop a framework using Page factory.Please help.

`

<suite name = "Adactin" verbose="1">
<parameter name="URL" value="http://www.adactin.com/HotelAppBuild2/"/>
<parameter name="PageTitle" value="AdactIn.com - Hotel Reservation System"/>
<test name = "RegressionTest">
<parameter name="Username" value="AdminSample"/>
<parameter name ="Password" value="AdminSample"/>
<classes>
<class name ="Tests.Test_HomePage"></class>
<class name="Tests.Test_HotelSelctPage"></class>
</classes>
</test>
</suite>

` Class:1

    `package Tests;

    import java.util.concurrent.TimeUnit;

    import org.openqa.selenium.By;
    import org.openqa.selenium.StaleElementReferenceException;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;
    import org.testng.Assert;
    import org.testng.annotations.BeforeSuite;
    import org.testng.annotations.BeforeTest;
    import org.testng.annotations.Parameters;
    import org.testng.annotations.Test;

    import PageFactory.HomePage;

    public class Test_HomePage 
{
     WebDriver driver;
     HomePage Obj;

  @BeforeSuite
  @Parameters({"URL","PageTitle"})
  public void setup(String URL,String PageTitle) 
  {
      driver= new FirefoxDriver();
      driver.get(URL);
      driver.manage().window().maximize();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      if(!(driver.getTitle().equalsIgnoreCase(PageTitle)))
      {
          Assert.fail("Home Page title is not as expected.Quitting the test..");
          driver.quit();
      }
      else
      {
          System.out.println(":: Home Page was displayed successfully ::");
          Obj=new HomePage(driver);
      }
  }

  @Test
  @Parameters({"Username","Password"})
  public void test_Login(String Username,String Password)
  {
      System.out.println("//Executing test_Login//");
    try 
    {
          Obj.LoginAction(Username, Password);

    } catch (NullPointerException e) 
    {
        System.out.println("exception details are : "+ e);
    }
      WebDriverWait wait=new WebDriverWait(driver,10);
      try
      {
          wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Logout")));
          if(!(driver.findElement(By.linkText("Logout")).isDisplayed()))
          {
              Assert.fail(":: Login is not successful.Logout button is not displayed ::");
              driver.quit();    
          }
          else
          {
              System.out.println(":: Login was successful ::");
             // driver.findElement(By.linkText("Logout")).click();
          }
        /*  if(!(driver.findElement(By.linkText("Click here to login again")).isDisplayed()))
          {
              Assert.fail(":: Logout was not successful ::");
              driver.quit();
          }     
          else
              System.out.println(":: Logout was successful ::");*/
      }   
      catch(StaleElementReferenceException e)
 {
    e.printStackTrace();  
    }
    /* finally
    {
    driver.quit();
    }*/
    }
    }`

Class:2

package Tests;

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

import PageFactory.HotelSelct_Page;

public class Test_HotelSelctPage extends Test_HomePage
{
//  HotelSelct_Page obj;
    //WebDriver driver=null;

  @Test
  public void Dropdown() 
  {
//    obj= new HotelSelct_Page(driver);
    //obj.Select_Location();  
      System.out.println("hi");

  }
}

Test Result:

    [TestNG] Running:
      G:\Work\Selenium\Workspace\Adactin\src\TestNGDataFile.xml

    :: Home Page was displayed successfully ::
    //Executing test_Login//
    exception details are : java.lang.NullPointerException
    //Executing test_Login//
    :: Login was successful ::
    hi

    ===============================================
    Adactin
    Total tests run: 3, Failures: 1, Skips: 0
    ===============================================


Exception Trace:

java.lang.NullPointerException
    at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:210)
    at org.openqa.selenium.support.ui.FluentWait.<init>(FluentWait.java:94)
    at org.openqa.selenium.support.ui.WebDriverWait.<init>(WebDriverWait.java:70)
    at org.openqa.selenium.support.ui.WebDriverWait.<init>(WebDriverWait.java:44)
    at Tests.Test_HomePage.test_Login(Test_HomePage.java:57)
    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)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
    at org.testng.TestNG.run(TestNG.java:1057)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)

Page-1 Code:

package PageFactory;

import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;

public class HomePage 
{
    WebDriver driver;

    By Username=By.id("username");
    By Password=By.id("password");
    By Loginbutton=By.id("login");
    By ForgotPassword_Link=By.linkText("Forgot Password?");
    By NewUser_RegLink=By.linkText("New User Register Here");

    public HomePage(WebDriver driver)
    {
        this.driver=driver;
    }

    public void setUsername(String strUsername)
    {
        try
        {
            driver.findElement(Username).sendKeys(strUsername);
        }
        catch(StaleElementReferenceException e)
        {
            e.printStackTrace();
            Assert.fail();
        }
    }
    public void setPassword(String strPassword)
    {
        try 
        {
            driver.findElement(Password).sendKeys(strPassword);
        } 
        catch (StaleElementReferenceException e) 
        {
            e.printStackTrace();
            Assert.fail();
        }
    }
    public void clickLogin()
    {
        try 
        {
            driver.findElement(Loginbutton).click();
        } 
        catch (StaleElementReferenceException e) 
        {
            e.printStackTrace();
            Assert.fail();
        }
    }

    public void LoginAction(String strUsername,String strPassword)
    {
        this.setUsername(strUsername);
        this.setPassword(strPassword);
        this.clickLogin();
    }

}

Page-2 Code:

package PageFactory;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;

public class HotelSelct_Page 
{
    WebDriver driver;
    By SearchHotel_Link     =By.linkText("Search Hotel");
    By BookedItenery_Link   =By.linkText("Booked Itinerary");
    By Change_PwdLink       =By.linkText("Change Password");
    By Logout_Link          =By.linkText("Logout");
    By Location_element     =By.xpath(".//*[@id='location']");
//  Select Location_DropDown=new Select(Location_element);
//  Select Hotel_DropDown   =new Select((WebElement) By.xpath(".//*[@id='hotels']"));
//Select Room_DropDown  =new Select((WebElement) By.xpath(".//*[@id='room_type']"));
//  Select NumberOfRooms_DropDown=new Select((WebElement) By.xpath(".//*[@id='room_nos']"));
    By CheckInDate_editBox  =By.id("datepick_in");
    By CheckOutDate_editBox =By.id("datepick_out");
//  Select Adults_DropDown  =new Select((WebElement) By.xpath(".//*[@id='adult_room']"));
//  Select Children_DropDown=new Select((WebElement) By.xpath(".//*[@id='child_room']"));
    By Search_Button        =By.id("Submit");
    By Reset_Button         =By.id("Reset");

    public HotelSelct_Page(WebDriver driver)
    {
        this.driver=driver;
    }

  public void Select_Location() 
  {
     /* WebElement Location_DropDown_Element =driver.findElement(Location_element);
      Select Location_DropDown = new Select(Location_DropDown_Element);
      Location_DropDown.selectByIndex(2);
      List<WebElement> Location_DropDownList = Location_DropDown.getOptions();
      for(WebElement s : Location_DropDownList)
          System.out.println(s.getText());*/
     // System.out.println("hi");
    /*  Select Loc_Dropdown = new Select(driver.findElement(Location_element));
      Loc_Dropdown.selectByIndex(2);
        */  
      //driver.findElement(Change_PwdLink).click();
      //System.out.println("hi");
  }
}
1
I think you are getting exception from function "Obj.LoginAction(Username, Password);" Can you post this function code ? - Sadik Ali
Hi Sadik, I just added it.Please check. - Manoj Kumar N
You can set a breakpoint at line WebDriver driver;, and then use a debugger to find a place where driver variable is cleared to null. - krokodilko

1 Answers

1
votes

Below is reason why you are getting Nullpointer exception.

  1. You have two testng test methods one "test_Login" and other "Dropdown"
  2. You inherited "Test_HomePage" class into "Test_HotelSelctPage" so for class "Test_HotelSelctPage" you have two testng methods one from base class and other from child class. so total you have three test methods.
  3. Your TestNg suite have one test, that contains both class it means you have three methods for testng suite.
  4. When you run testng suite it run as below:

    First Start execution of class"Test_HotelSelctPage" as "Dropdown" methods comes first in alphabetical order in first thread. execute"setup" method and initialize driver object then execute both test one by one successfully.

    Now next it start execution of class "Test_HomePage" for test "test_Login" in second thread. For second thread setup method will not execute as by the definition of beforesuite annotation it run only once for a testng suite. It direct start execution "test_Login" methods and there is not any initialization of webdriver object for second thread and in resultant NullPointer exception generated.