Nilesh Khoriya Nilesh Khoriya - 26 days ago 8
Java Question

Selenium TestNG framework unable to call driver object in multiple test

I am trying to execute the following program but getting a null pointer error. where @test is not able to access the object - driver. what could be the possible error i am making. Error -

JavaScript warning: https://www.google.com/xjs/_/js/k=xjs.s.en_US.MHBUsB8Me90.O/m=sx,c,sb,cdos,cr,elog,hsm,jsa,r,qsm,d,csi/am=wCJGjhccAPk_IRQStxAWyAImDiA/rt=j/d=1/t=zcms/rs=ACT90oGwMPBWhsFBKoM1svJAFUVoVQRQug, line 7: mutating the [[Prototype]] of an object will cause your code to run very slowly; instead create the object with the correct initial [[Prototype]] value using Object.create
https://www.google.com/?gws_rd=ssl
FAILED: websiteTitle

java.lang.NullPointerException
at myPackage.TestNGforHDFC.websiteTitle(TestNGforHDFC.java:24)
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:108)

package myPackage;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class TestNGforHDFC {
public WebDriver driver;
public String urlUnderTest = "http://www.google.com";
public String projLocation = "C:\\Users\\Nikita Agrawal\\Selenium\\geckodriver.exe";
@BeforeTest
public void login()
{
System.setProperty("webdriver.gecko.driver", projLocation);
WebDriver driver = new FirefoxDriver();
driver.get(urlUnderTest);
System.out.println(driver.getCurrentUrl());
}

@Test
public void websiteTitle()
{
System.out.println(driver.getTitle());
}
}

Answer Source

The class variable driver is never initialized, you're defining a new variable called driver inside the login method.

Use:

public void login(){
    driver = new FirefoxDriver();
    ....
}

Instead of:

public void login(){
    WebDriver driver = new FirefoxDriver();
    ....
}