WebDriver : Java with TestNG, Getting Null Pointer exception in Driver instance.

9,543 views
Skip to first unread message

parikshit chakraborty

unread,
Jul 23, 2012, 1:08:37 AM7/23/12
to webd...@googlegroups.com
Hello All,

I am facing an issue in writing Selenium Code using Java and TestNG. The scenario is as below

I have 3 java classes A,B and C. Class A has a method called startDriver with @BeforeClass annotation. Class B extends Class A and Class C extends Class B. Class C is executable java class having one method with @Test annotation. The Webdriver instance is getting initialized in startDriver method in Class A based on the parameters passed from testng.xml.
When I start script execution, WebDriver instance gets initialized before the method in Class C having @Test annotation starts and I have driver instance available in Class C as well. In Class C, I am reading data from an excel having Keywords and its corresponding parameters. I have one more java class D (not extending either A, B or C)  having a static method with switch case to call appropriate method from either Class A, B or C depending on the Keyword. The keywords are read in Class C and passed to Class D method to invoke respective methods. Now since the method in Class D is a static method, so I need to create an Object of either Class A, B or C to invoke keyword specific methods in them. As I do so, I get a Null Pointer Exception in Driver instance.

I am really stuck at this point and don't know how to proceed further and accomplish this task. Please reply with any solution.


Thanks,
Parikshit

Mike Riley

unread,
Jul 23, 2012, 1:58:58 AM7/23/12
to webd...@googlegroups.com
That is probably because each class is a different thread.  If you make the driver instance a static in class A it will probably work.  However, I am not sure about the @BeforeClass for extended classes.  It might consider B and C to be completely different classes and not execute the method in A.  It would be more certain if you used @BeforeGroup or @BeforeSuite.  I use the last one for my classes, which also extend a base class with the @BeforeSuite and @AfterSuite methods in it.

Mike

Tarun Kumar

unread,
Jul 23, 2012, 2:00:38 AM7/23/12
to webd...@googlegroups.com
A small snippet of your code may help us in answering.

parikshit chakraborty

unread,
Jul 23, 2012, 3:13:05 AM7/23/12
to webd...@googlegroups.com
Hi Tarun,

Plz find below small snippets of 3 classes I am talking about, I have not included Class B here rather, Class A, B and D are present. Let me know if this helps

<-------------------- Class A --------------------------->
public class BaseTest
{
protected WebDriver driver;
protected Selenium selenium;
protected long timeout = 90;
protected WebElement webElement;
protected Properties adjustment;
protected Properties commercialinvoice;
protected Properties bankaccount;
protected Properties bankpayment;
protected Properties paymentsettings;
protected Properties config;
protected Properties common;
protected int flg;
protected boolean isFirefox = false;
private boolean isParallel = Boolean.FALSE;
protected String platform = null;
public static String testCaseName= null;
protected LinkedHashMap<String, String> testCaseMap = new LinkedHashMap<>();
protected Map<String, List<ParamDataObject>> keywordMap = new HashMap<>();
protected List<String> usrRoles = new ArrayList<>();

public BaseTest() throws Exception
{
initiaLize();
}

public void initiaLize() throws Exception 
{

common = new Properties();
common.load(new FileInputStream(System.getProperty("user.dir").concat("/src/resources/org/gtn/p2p/common/common.properties")));

config = new Properties();
config.load(new FileInputStream(System.getProperty("user.dir").concat("/src/resources/org/gtn/p2p/common/config.properties")));

adjustment = new Properties();
adjustment.load(new FileInputStream(System.getProperty("user.dir").concat("/src/resources/org/gtn/p2p/commercialinvoice/adjustment/adjustment.properties")));

commercialinvoice = new Properties();
commercialinvoice.load(new FileInputStream(System.getProperty("user.dir").concat("/src/resources/org/gtn/p2p/commercialinvoice/commercialinvoice.properties")));

bankpayment = new Properties();
bankpayment.load(new FileInputStream(System.getProperty("user.dir").concat("/src/resources/org/gtn/p2p/bankpayment/bankpayment.properties")));

bankaccount = new Properties();
bankaccount.load(new FileInputStream(System.getProperty("user.dir").concat("/src/resources/org/gtn/p2p/bankaccount/bankaccount.properties")));

paymentsettings = new Properties();
paymentsettings.load(new FileInputStream(System.getProperty("user.dir").concat("/src/resources/org/gtn/p2p/paymentsettings/paymentsettings.properties")));

}

@BeforeClass
@Parameters({ "browser", "URL"})
public void instantiateWebDriver(String browser, String url) throws Exception 
{

try 
{
if (browser.equalsIgnoreCase(Constants.FIREFOX_BROWSER))
{
FirefoxProfile profile = new FirefoxProfile();//new File("C:/WebProfile"));
driver = new FirefoxDriver(profile);
}
else if (browser.equalsIgnoreCase(Constants.IE_BROWSER))
{
driver = new InternetExplorerDriver();
}
else if (browser.equalsIgnoreCase("*chrome"))
driver = new ChromeDriver();
selenium = new WebDriverBackedSelenium(driver, url);
driver.get(url);
maximiseWindow();
} catch (Exception e) {
e.printStackTrace();
}
}

@AfterClass(alwaysRun = true)
public void stopWebDriver() 
{
driver.manage().deleteAllCookies();
driver.close();
}
public boolean appLogin(List<String> param) throws Exception{

driver.findElement(By.xpath(common.getProperty("Username"))).sendKeys(userName);
driver.findElement(By.xpath(common.getProperty("Username"))).sendKeys(pwd);
driver.findElement(By.xpath(common.getProperty("LoginButton"))).click();
waitForElementPresent(By.xpath(common.getProperty("SearchButton")));
}
}
<----------- Class B ---------------------------->
public class AddChargesandDiscountPOI extends BaseTest {

public AddChargesandDiscountPOI() throws Exception {
super();
// TODO Auto-generated constructor stub
}
private void fetchKeywordAndData() throws Exception 
{
List<ParamDataObject> objList = new ArrayList<>();
List<String> paramList = new ArrayList<>();
Set<String> keySet = testCaseMap.keySet();
Iterator<String> iterator = keySet.iterator();
while (iterator.hasNext()) 
{
String tcid = (String) iterator.next();
objList = keywordMap.get(tcid);
for (ParamDataObject paraObj : objList) 
{
Reporter.log("Keyword executed : " + paraObj.getKeywordName());
paramList = paraObj.getParamList();
if(Controller.mainController(paraObj.getKeywordName(), paramList))
continue;
else
break;
}
}
}
@Test
public void mainAddChargesandDiscountPOI() throws Exception {
String filepath = System.getProperty("user.dir").concat(adjustment.getProperty("Adj_DataFilePath"));
int sheetnum = 0;
try {
readFromExcel(filepath, sheetnum);
System.out.println("Driver=========>" + driver);
fetchKeywordAndData();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
}


<------------------- Class D --------------------------->
public class Controller {

public static boolean mainController (String Keyword,  List<String> param_array) throws Exception{

switch (Keyword) {

case "Login":
BaseTest baseLogin = new BaseTest();
if (baseLogin.appLogin(param_array))
return Boolean.TRUE;
else 
return Boolean.FALSE;
}
}


Thanks,
Parikshit

Tarun Kumar

unread,
Jul 23, 2012, 3:37:23 AM7/23/12
to webd...@googlegroups.com
I suppose it is because you instantiate BaseClass in class D and expect driver to have been initialized too which is not the case.
This is irrespective of method 'mainController' being static.
Just two classes, base class and class D where you instantiate BaseClass would demonstrate this behavior.
I would suggest to rethink the design

parikshit chakraborty

unread,
Jul 23, 2012, 3:45:34 AM7/23/12
to webd...@googlegroups.com
Yes Tarun, you are correct. Because of the instantiation of BaseClass in Class D i am getting Null pointer exception in applogin method. The purpose of Class D is to receive Keyword and based on that it should invoke methods from other classes. That's why Class D is not extending Class A. Since, the method in Class D is static, so in order to call non-static methods from some other class, I need to create an instance of that class and then call that method. In doing so I am getting null pointer exception in Driver instance in applogin method. Main purpose of Class D is to re-direct based on Keywords.

I just want to know is there a way to accomplish this by keeping Class D separate just for invoking methods. If yes, then how...

Thanks,
Parikshit

Tarun Kumar

unread,
Jul 23, 2012, 3:55:52 AM7/23/12
to webd...@googlegroups.com
You could try with page object.
login method could be in its own Login class, which could have constructor taking driver object.
Now you can instantiate Login class from class D, considering you have access to driver object in class D.

Naresh

unread,
Jul 23, 2012, 3:55:58 AM7/23/12
to webd...@googlegroups.com
Hello Parikshit,

Can you make driver as static field. I think that will solve your problem.

Thanks,
Naresh

pna...@gmail.com

unread,
Jul 23, 2012, 3:57:32 AM7/23/12
to webd...@googlegroups.com
Alternative use Spring to manage dependencies. You can tell sprint about which class needs what ? And it will manage that for you.
Sent from my BlackBerry® wireless device

From: Tarun Kumar <tku...@gmail.com>
Date: Mon, 23 Jul 2012 00:55:52 -0700 (PDT)
Subject: [webdriver] Re: WebDriver : Java with TestNG, Getting Null Pointer exception in Driver instance.
--
You received this message because you are subscribed to the Google Groups "webdriver" group.
To view this discussion on the web visit https://groups.google.com/d/msg/webdriver/-/yqDwjtNSvCoJ.
To post to this group, send email to webd...@googlegroups.com.
To unsubscribe from this group, send email to webdriver+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/webdriver?hl=en.

Tarun Kumar

unread,
Jul 23, 2012, 6:32:50 AM7/23/12
to webd...@googlegroups.com
Making driver static would cause errors when running tests in parallel in multiple browsers.

Pankaj

unread,
Jul 26, 2012, 12:37:55 AM7/26/12
to webd...@googlegroups.com
Hi,

When I am executing my selenium code with TestNg I am getting following error:

---------------------------------------------------------------------------------------------------------------------------------------------------
FAILED: SeenResponse("EX00190A", "aug$2012a", "B000125JulClaim01")
java.lang.NullPointerException
    at Tests.SYResSeen.SeenResponse(SYResSeen.java:26)
    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:80)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:702)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:894)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1219)
    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:53)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:87)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1192)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1117)
    at org.testng.TestNG.run(TestNG.java:1025)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:109)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:202)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:173)


===============================================
    Default test
    Tests run: 1, Failures: 1, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 1, Failures: 1, Skips: 0
===============================================
----------------------------------------------------------------------------------------------------------------------------------

My code is bellow, my script stops at the step in red. I have verified the XPath I have given is correct. Can you please help with this-

package Tests;

 

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;

 

public class SYResSeen extends TestBase{

     

      @Test(dataProvider = "getData")

      public void SeenResponse(String user, String pwd, String ucr) throws InterruptedException{

           

            getObject("Username_Textbox").sendKeys(user);

            getObject("Password_TextBox").sendKeys(pwd);

            getObject("Login_Button").click();

           

            getObject("CAS_Link").click();

           

            getObject("UCR_TextBox").sendKeys(ucr);

            getObject("Search_Button").click();

           

            getObject("UCR_Link").click();

           

            getObject("TR01SYStatus_Link").click();

           

            Thread.sleep(20000L);

           

            getObject("Phone_Textbox").sendKeys("123456");

 

 

            getObject("PublicComm_Textbox").sendKeys("test");

            getObject("SeenResponse_Radio").click();

            getObject("Submit_Button").click();

           

            Thread.sleep(10000L);

           

            getObject("CancelConfirm_PopUpButton").click();

      }

 

      @DataProvider

      public Object[][] getData(){

            Object data[][] = new Object[1][3];

            // 1st Row

            data[0][0]="EX00190A";

            data[0][1]="aug$2012a";

            data[0][2]="B000125JulClaim01";

           

            return data;

           

      }

}


Thanks & Regards

Pankaj Khanna

Mark Collin

unread,
Jul 26, 2012, 3:49:23 AM7/26/12
to webd...@googlegroups.com

I would guess thate getObject(“Phone_Textbox”) is not returning anything and then when the sendKeys is triggered is tries to send keys to a null object resulting in a null pointer error.

 

You haven’t shown the code for getObject but I suspect it is not throwing an exception when it is not getting set which is why you are getting the null pointer error.

 

From: webd...@googlegroups.com [mailto:webd...@googlegroups.com] On Behalf Of Pankaj
Sent: 26 July 2012 05:38
To: webd...@googlegroups.com
Subject: [webdriver] Re: WebDriver : Java with TestNG, Getting Null Pointer exception in Driver instance.

 

Hi,

--

You received this message because you are subscribed to the Google Groups "webdriver" group.

To view this discussion on the web visit https://groups.google.com/d/msg/webdriver/-/MmnRLYuVwj8J.

Message has been deleted

GoldD

unread,
Jul 26, 2012, 6:01:01 AM7/26/12
to webd...@googlegroups.com
can you show your getObject(...) ?

Mike Riley

unread,
Jul 26, 2012, 12:42:32 PM7/26/12
to webd...@googlegroups.com
Plus you are doing a sleep for 20 seconds (!?!) just before that.  So however getObject works it must be having a problem finding that object (an element on the page?).  You should be doing something like an implicit wait (I am guessing) to wait for the object to appear and if it does not you should be handling it via a try-catch.

Mike

To unsubscribe from this group, send email to webdriver+unsubscribe@googlegroups.com.

Rajan Mahindra

unread,
Jul 20, 2014, 8:25:55 AM7/20/14
to webd...@googlegroups.com
Hello Tarun.

I think I have a question you can answer (Considering your comments i read above).

I have two test scripts. One for Login to the google account, second is to navigate to Outbox.
In my Outbox script, i am calling the @test function from my first script, i.e Login script as this function helps me to log into the google account, so that i can further navigate to Outbox.
Now the problem starts, as soon as my Outbox script begin to execute from the suite, it throws Null Pointer Exception. 
I have declared Webdriver as not being static.

However, i get solution to my problem when i declare the Webdriver as static.(But this now causes problem in Parallel execution).

What should i do? And why is it that when Webdriver is not being static, the Null Pointer Exception occurs?

Thanks 
Rajan

Krishnan Mahadevan

unread,
Jul 21, 2014, 9:17:54 PM7/21/14
to webd...@googlegroups.com
If you are trying to automate a mailing web app using selenium I would say STOP. There are elegant ways of interacting with a mail server. You should be using JavaMailAPIs 

~ Krishnan

iSent. iPhone. iReget.iTypos!
--
You received this message because you are subscribed to the Google Groups "webdriver" group.
To unsubscribe from this group and stop receiving emails from it, send an email to webdriver+...@googlegroups.com.

To post to this group, send email to webd...@googlegroups.com.

darrell

unread,
Jul 22, 2014, 8:35:40 AM7/22/14
to webd...@googlegroups.com
If you instantiate an instance of WebDriver in say your @Before method then declare a variable in a different class which does not extend the first class, you have two variables. One is initialized and not null but the other class is uninitialized and null. What you need to do is pass the initialized instance of WebDriver from the first class to the second class. This can be done via a constructor or calling some initialization method before you use the second class.

This is basic Java and not really WebDriver specific. If you don't understand the execution order of a framework like JUnit or TestNG then it require you to get a better understanding of those frameworks (still not WebDriver specific).

All that said, Krishnan is correct that the only good reason to automate a web based email app is if you are testing the email app. If you are testing an app which requires you to use email then you want to setup a mock email. You want to use something like: http://quintanasoft.com/dumbster/. This is a mock SMTP email service. You set up a computer to be an SMTP server. You setup your application under test to use the fake SMTP email server. When the app sends an email dumpster will generate an email file on the machine you set up dumpster. You can then use scp, samba, UNC, etc. to access the files and retrieve email. If dumpster is setup on the same machine as your test code then the test code just needs to access the local file system (File class in Java). Opening a text file will be easier and faster. Using a real SMTP email service via web access is just increasing the number of failure points and the places your tests can fail have nothing to do with the application you are testing.
Reply all
Reply to author
Forward
0 new messages